Json.NET get nested jToken value

后端 未结 1 1811
无人及你
无人及你 2020-11-28 16:19

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

相关标签:
1条回答
  • 2020-11-28 17:14

    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.

    0 讨论(0)
提交回复
热议问题