Reputation: 302
What's the best way to deal with semi-structured JSON data in C#? If you have nested objects and eventually one will return null, how would you deal with that? How would you handle unexpected nested null objects? Is cumbersome to write multiple if statements just to check to see if it's null because the nested objects can be 'N' amount. Working with 3rd party APIs, you can't always expect them to return a structured data set.
Example:
[{
"ID": 0
, "WeatherName": "Rain"
, "Location": "San Francisco"
, "Details": null
},{
"ID": 1
, "WeatherName": "Snow"
, "Location": "New York"
, "Details": {
"Population": 1234567
, "Traffic": null
}
},{
"ID": 2
, "WeatherName": "Fire"
, "Location": "Sacramento"
, "Details": {
"Population": 1234567
,"Traffic": {
"Accidents": 10
,"Death": 10
}
}
}]
In this case, I would have to write one if statement to check the parent object is null, then write another if statement to check if the child object is null, then another if statement to check the other child statement is null. As you can see, it can be a pain to write multiple if statements to check for null.
Upvotes: 0
Views: 279
Reputation: 977
This doesn't look like an unstructured data set to me. The possibility of some properties being null is manageable (and too common), as opposed to having different kinds of objects without any overlapping properties in the very same array!
Try modelling your response like this (done with this tool):
public class Traffic {
public int Accidents { get; set; }
public int Death { get; set; }
}
public class Details {
public int Population { get; set; }
public Traffic Traffic { get; set; }
}
public class Response {
public int ID { get; set; }
public string WeatherName { get; set; }
public string Location { get; set; }
public Details Details { get; set; }
}
Then, to parse (using Newtonsoft.JSON) and access some properties that might be null in a safe manner (edited for more safety, kudos @mjwills):
var response = JsonConvert.DeserializeObject<Response[]>(myJsonString);
int? maybePopulation = response.FirstOrDefault()?.Details?.Population; // either int, or null
In other words, to deal with having to check for null and avoid writing null checks, use null-conditional operator.
Upvotes: 4