2

I have a sample JSON that when i deserialize i get "object reference not set to instance of an object" because i found out some that sometimes the field is missing then it will reappear again.

the json is similar to this

{
    "title": "Example",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
        "age": {
            "description": "Age in years",
            "type": "integer",
            "minimum": 0
        }
    }

}

if i deserialize this and map it to the corresponding fields the result is OK

but if for example the "Age" is missing

{
    "title": "Example",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
    },
    "required": ["firstName", "lastName"]
}

it will throw an error "object reference not set to instance of an object" how do i ignore the age if it's missing in JSON?

5
  • What library do you use? Commented Jun 19, 2015 at 2:23
  • if its real POCO object I check if this any property there with null, I assigned then with blank object. like if(MyObject.Properties.Age==null) { MyObject.Properties.Age = new Age();} then deserialize it. Commented Jun 19, 2015 at 2:25
  • i use json.net library Commented Jun 19, 2015 at 2:25
  • The "Age" should be null in your case. What is your lib version? V6.0.8 works in a similar case. Commented Jun 19, 2015 at 2:43
  • i tried adding new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore}); at the end of deserialization it still throws an error. Commented Jun 19, 2015 at 2:44

1 Answer 1

2

Update when you said you using json.net

I will say there is setting for Json.net try the below

JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore

if its real POCO object, I check if any property there with null, I assigned then with blank object. like

if(MyObject.Properties.Age==null)
{
   MyObject.Properties.Age = new Age();
}

then deserialize it.

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

3 Comments

do i add this on my class?
[JsonProperty("age", NullValueHandling = NullValueHandling.Ignore)]
yes... you can add either way.. i mean either add as attribute on property of 'AGE' or whatever it is.. or you can set the centralize for all using JsonSerializerSetting static class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.