pixel
pixel

Reputation: 10605

C# Handle null values in specific JSON below

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,

Upvotes: 0

Views: 43

Answers (2)

Corey
Corey

Reputation: 16584

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.

Upvotes: 1

pixel
pixel

Reputation: 10605

resolved by using

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

Upvotes: 1

Related Questions