2

I have this JSON :

{
    "Foo": "A value",
    "Bar": 42
}

To deserialize it, I have this class :

public class SomeClass
{
    public string Foo { get; set; }
    public int Bar { get; set; }
}

I'm deserializing it using :

string json1 = "{\"Foo\":\"A value\",\"Bar\":42}";
var MyObj1 = JsonConvert.DeserializeObject<SomeClass>(json1);
Debug.WriteLine("Foo1 : " + MyObj1.Foo); //Foo1 : A value
Debug.WriteLine("Bar1 : " + MyObj1.Bar); //Bar1 : 42

I need a specific treatment when a field is missing from JSON.

In example :

{
    "Foo": "Another value"
}

When using the same code than above, Bar is set to 0. It could have been set to 0 in the original JSON, so I can't tell with this value if it was existing or not.

string json2 = "{\"Foo\":\"Another value\"}";
var MyObj2 = JsonConvert.DeserializeObject<SomeClass>(json2);
Debug.WriteLine("Foo2 : " + MyObj2.Foo); //Foo2 : Another value
Debug.WriteLine("Bar2 : " + MyObj2.Bar); //Bar2 : 0

How can I achieve it?

2
  • 2
    As an aside, if you want the app to fail when members are missing, you can do this stackoverflow.com/questions/18147404/… Commented Oct 28, 2018 at 16:28
  • @DavidG thank you. I saw this topic, but the missing member, in my case, is a normal behaviour and shouldn't throw an exception at deserialization Commented Oct 29, 2018 at 7:49

1 Answer 1

5

The simplest option would be to make it an int? property, then check whether the value is null afterwards:

public class SomeClass
{
    public string Foo { get; set; }
    public int? Bar { get; set; }
}

...

var deserialized = JsonConvert.DeserializeObject<SomeClass>(json);
if (deserialized.Bar == null)
{
    // Whatever you want to do if it wasn't set
}

Of course, the JSON could explicitly set the value to null, but I expect you'd probably be happy handling that as if it was missing.

Sign up to request clarification or add additional context in comments.

1 Comment

-facepalm- Obviously, int? Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.