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 there is a more direct way to get a child jToken by path and/or de-serialize it without foreaching every level.
I tried this approach but it returns null:
JObject jObj = JObject.Parse( text );
JToken myVal;
jObj.TryGetValue( "response.docs", out myVal );
Here is my working overly complicated code, including de-serialization:
JObject jObj = JObject.Parse( text );
foreach( var kv in jObj ) {
if( kv.Key == "response" ) {
foreach( JToken jt in kv.Value ) {
if( jt.Path == "response.docs" ) {
JEnumerable<JToken> children = jt.Children();
foreach( JToken t in children ) {
//THIS WORKS BUT IS NOT ELEGANT
Solr_User[] su = t.ToObject<Solr_User[]>();
}
}
}
}
}
And here is the JSON raw response just for reference:
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"q":"*:*",
"indent":"on",
"wt":"json"}},
"response":{"numFound":4,"start":0,"docs":[
{
"id":3,
"first_name":"Bob",
"_version_":"1558902640594649088"},
{
"id":4,
"first_name":"Sam",
"_version_":"1558902640613523456"},
{
"id":2,
"first_name":"Fred",
"_version_":"1558902640613523457"},
{
"id":1,
"first_name":"Max",
"_version_":"1558902640613523458"}]
}}