-3

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.

mjwills
  • 23,389
  • 6
  • 40
  • 63
tcode
  • 5,055
  • 19
  • 65
  • 124

1 Answers1

1

You can use ShouldSerialize method.

Add this to your DataPoint class

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

And then add Formatting.Indented to your serialization call:

ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints, Formatting.Indented);
mjwills
  • 23,389
  • 6
  • 40
  • 63
M Bakardzhiev
  • 632
  • 5
  • 13
  • 3
    I fail to see how this solution is cleaner than the solution in the [suggested duplicate question](https://stackoverflow.com/questions/6507889/how-to-ignore-a-property-in-class-if-null-using-json-net). Use JsonConvert's functionality to ignore nulls rather than adding custom logic to achieve the same result. – UncleDave Apr 06 '18 at 12:26
  • 1
    @UncleDave It is more general, next time the property he wants to ignore might not be null but hold a different value. It works in his case and also provides an example he can use for other cases. – M Bakardzhiev Apr 06 '18 at 12:31
  • 1
    I agree @MBakardzhiev - for the OP's _specific_ case this is unnecessary (and likely slower due to reflection), but for the _broader_ problem space this is a great way of attacking the problem. – mjwills Apr 06 '18 at 12:54
  • This answer could be **even better** if it was tweaked to include why `X` was serialised to start with (i.e. `JsonConvert` doesn't care which constructor was called - it just cares about the public properties). – mjwills Apr 06 '18 at 13:00