【发布时间】: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