0

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?

1
  • So, each review can have several comments, and each of those comments can have a star rating? So in effect each review can have multiple ratings? That seems very odd - are you sure that's what you want? Commented Jan 31, 2020 at 11:27

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.