Warm tip: This article is reproduced from stackoverflow.com, please click
arrays c# json serialization

Accessing nested JSON array

发布于 2020-03-30 21:16:37

I have the following JSON:

{
 "reviews": [
  {
   "reviewId": "123",
   "authorName": "author",
   "comments": [
    {
     "userComment": {
      "text": "text",
      "lastModified": {
       "seconds": "1580461776",
       "nanos": 1
      },
      "starRating": 5,
      "reviewerLanguage": "GB",
      "appVersionCode": "",
      "appVersionName": "",
      "thumbsUpCount": 0,
      "thumbsDownCount": 0
     }
    }
   ]
  }
 ]
}

From this all I want to access is the starRating (but with the potential for multiple reviews) I have managed to deserialize the JSON into a C# object correctly and have checked this when debugging my code.

So far I have:

var appReview = JsonConvert.DeserializeObject<appData>(appJson);
var reviews = appReview.Reviews;
int reviewCount = reviews.Length;
for (int i = 0; i < reviewCount; i++)
{
    Console.WriteLine(reviews[0].Comments[0].UserComment.StarRating); 
}

However I don't just want the star rating of this specific review as in the future there will be more reviews and star ratings, therefore I need to select all of the reviews in the JSON and get an average of the star rating? Because of that, I'm not sure accessing them with the [0] index is correct. Hopefully I have explained that well enough - can anyone please point me in the correct direction?

Questioner
Jordan1993
Viewed
26
haldo 2020-01-31 19:28

If you are comfortable using linq then I would suggest something like this:

var ratings = appReview.Reviews
                       .SelectMany(r => r.Comments.Select(c => c.UserComment.StarRating));

This should get you a list of ratings. This works by selecting the StarRating from the Comments then SelectMany flattens the arrays to a single array.

Then you can use get the average like so:

var average = ratings.Average();

Try it online