-1

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

Owais Ahmed
  • 1,364
  • 1
  • 30
  • 62

2 Answers2

4

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!

Community
  • 1
  • 1
TranQ
  • 139
  • 1
  • 7
2

I suspect the problem is in your Json you have a space in the field "test " which is causing a null reference exception.

I'm not entirely sure whether is it copy paste mistake or your getting Json string in this format.

Check this working code on removing the space.

Hari Prasad
  • 16,716
  • 4
  • 21
  • 35