I have the following C# class which contains 2 constructors:
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;
}
Inside my MVC Controller I need to create an instance of the DataPoint
class and use the 2nd constructor, i.e., public DataPoint(double y, string label)
.
I do this in the code below and then serialize the object into JSON.
List<DataPoint> dataPoints = new List<DataPoint>{
new DataPoint(10, "cat 1"),
new DataPoint(20, "cat 2")
};
ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);
When I view the returned JSON it looks like this
[{"x":null,"y":10.0,"label":"cat 1"},{"x":null,"y":20.0,"label":"cat 2"}]
My problem is that I don't want the x
element included in my JSON data.
Why is this happening when I am not instantiating the 1st constructor in the DataPoint
class?
Thanks for your help.