I am working at parsing a json http response with Json.NET and have working code, but am pretty sure I am going about it in an overly complicated way. My question is if ther
You can use SelectToken() to select a token from deep within the LINQ-to-JSON hierarchy for deserialization. In two lines:
var token = jObj.SelectToken("response.docs");
var su = token == null ? null : token.ToObject<Solr_User []>();
Or in one line, by conditionally deserializing a null JToken when the selected token is missing:
var su = (jObj.SelectToken("response.docs") ?? JValue.CreateNull()).ToObject<Solr_User []>();
Sample fiddle.
In c# 6 or later it's even easier to deserialize a nested token in one line using the null conditional operator:
var su = jObj.SelectToken("response.docs")?.ToObject<Solr_User []>();
Or even
var su = jObj?["response"]?["docs"]?.ToObject<Solr_User []>();
Note that SelectTokens()
is slightly more forgiving than the JToken index operator, as SelectTokens()
will return null for a query of the wrong type (e.g. if the value of "response"
were a string literal not a nested object) while the index operator will throw an exception.