Owais Ahmed Owais Ahmed - 5 months ago 28
JSON Question

c# Json reading child object

I am trying to read child elements in the Json object below. Below is the Json example. I want to read

RecommendedCount
and
TotalReviewCount
in
testdata1, testdata2 and testdata3.


{
"HasErrors": false,
"Includes": {
"test ": {
"testdata1": {
"ReviewStatistics": {
"RecommendedCount": 0,
"TotalReviewCount": 2
}
},
"testdata2": {
"ReviewStatistics": {
"RecommendedCount": 0,
"TotalReviewCount": 2
}
},
"testdata3": {
"ReviewStatistics": {
"RecommendedCount": 0,
"TotalReviewCount": 2
}
}
}
}
}


I tried the code below.

RecommendedCount = apiResponse.Includes.Products[key].ReviewStatistics.RecommendedCount,
TotalReviewCount = apiResponse.Includes.Products[key].ReviewStatistics.TotalReviewCount


But this is very slow as the Json response has more than 1000 lines so it is taking time. I want to know is there any linq i can use to find the relevant data or any other methods i can use?

Thanks in advance.

var jObj = (JObject)JsonConvert.DeserializeObject(rawJson);
foreach (var child in jObj["test"].Children())
{

}


The above is the deserialize code i am trying to use but getting
Object reference not set to an instance of an object
. error

Answer

My solution:

JObject obj = JObject.Parse(jsonString);
var recList= obj.SelectTokens("$..ReviewStatistics.RecommendedCount").ToList();
var totalList= obj.SelectTokens("$..ReviewStatistics.TotalReviewCount").ToList();       

Then you can get the data that you want. For example, if you want RecommendedCount from testdata2, you do like this

var dataYouWant = (int)recList[1]; 

References:

If there is anything wrong, please feel free to correct my answer. Thanks!