0

I am trying to get thumb image urls in JSON below. What I have below works well if the "image" is not null and if "thumb" is not null. But if either is null, I get NullException.

Here is example of simplified JSON:

{
  "total_items": "24",
  "page_number": "1",
  "page_size": "10",
  "page_count": "3",
  "cars": {
    "car": [
      {
        "image": { 
          "thumb": {
            "width": "32",
            "url": "<image_url>/honda1.jpg",
            "height": "32"
          }
        }
      },
      {
        "image": null, 
      }
    ]
  }
}

and here is how I deserialize it using Newtonsoft.JSon:

dynamic data = (JObject)JsonConvert.DeserializeObject(json);
foreach (dynamic d in data.cars.car)
{
    Car c = new Car();
    c.ThumbUrl = d.image.thumb.url; //image AND thumb could be null
}

I have read few posts on how to handle this and tried adding [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] in my Car class above the Url property but that did not solve anything. Thanks,

2 Answers 2

1

In C# we now have null conditional operators such as ?. which are designed for this sort of things:

c.ThumbUrl = d.image?.thumb?.url;

This is a much simpler method than determining whether any of the objects in the path is a null, such as this sort of thing used before null conditional became available in the latest version of C#:

c.ThumbUrl = d.image == null ? (string)null : d.image.thumb == null ? (string)null : d.image.thumb.url;

Personally I haven't tried this with dynamics. I imagine that it should work, since ultimately it expands to basically the same code.

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

Comments

1

resolved by using

e.ThumbUrl = (string)d.SelectToken("image.thumb.url");

Comments

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.