【问题标题】:How to avoid serialising specific fields when generating JSON [duplicate]生成 JSON 时如何避免序列化特定字段 [重复]
【发布时间】:2018-04-06 11:19:15
【问题描述】:

我有以下包含 2 个构造函数的 C# 类:

public class DataPoint
{
    public DataPoint(double x, double y)
    {
        this.X = x;
        this.Y = y;
    }

    public DataPoint(double y, string label)
    {
        this.Y = y;
        this.Label = label;
    }

    //Explicitly setting the name to be used while serializing to JSON.
    [DataMember(Name = "x")]
    public Nullable<double> X = null;

    //Explicitly setting the name to be used while serializing to JSON.
    [DataMember(Name = "y")]
    public Nullable<double> Y = null;

    //Explicitly setting the name to be used while serializing to JSON.
    [DataMember(Name = "label")]
    public string Label;
}

在我的 MVC 控制器中,我需要创建 DataPoint 类的实例并使用第二个构造函数,即 public DataPoint(double y, string label)

我在下面的代码中执行此操作,然后将对象序列化为 JSON。

List<DataPoint> dataPoints = new List<DataPoint>{
            new DataPoint(10, "cat 1"),
            new DataPoint(20, "cat 2")

        };

ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);

当我查看返回的 JSON 时,它看起来像这样

[{"x":null,"y":10.0,"label":"cat 1"},{"x":null,"y":20.0,"label":"cat 2"}]

我的问题是我不希望我的 JSON 数据中包含 x 元素。

当我没有实例化 DataPoint 类中的第一个构造函数时,为什么会发生这种情况?

感谢您的帮助。

【问题讨论】:

  • 感谢您的反对。

标签: c# json constructor


【解决方案1】:

你可以使用ShouldSerialize方法。

将此添加到您的 DataPoint 类中

public bool ShouldSerializeX()
{
    return (X != null);
}

然后将Formatting.Indented 添加到您的序列化调用中:

ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints, Formatting.Indented);

【讨论】:

  • 我看不出这个解决方案比suggested duplicate question 中的解决方案更干净。使用 JsonConvert 的功能来忽略空值,而不是添加自定义逻辑来实现相同的结果。
  • @UncleDave 比较笼统,下次他要忽略的属性可能不是null而是持有不同的值。它适用于他的案例,也提供了他可以用于其他案例的示例。
  • 我同意@MBakardzhiev - 对于 OP 的 specific 情况,这是不必要的(并且可能由于反射而变慢),但对于 更广泛的 问题空间这是解决问题的好方法。
  • 这个答案可能会更好如果它被调整为包括为什么X被序列化以开始(即JsonConvert不关心哪个构造函数被调用 -它只关心公共属性)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多