noob_23
noob_23

Reputation: 137

Parsing through complex json in C#

I am attempting to parse through the following to determine the Name and Goals of the top scoring Player for the specific "AC Milan" in this json file that contains many other teams and countries. The main issue I have been running into when I parse it as a JObject is the inability to parse a JObject as a JArray as this json file is pretty messy.

Unhandled exception. System.InvalidCastException: Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.

enter image description here

Upvotes: 1

Views: 212

Answers (1)

Serge
Serge

Reputation: 43969

you have a json array, so you have to use for parsing JArray, not JObject

var jsonParsed=JArray.Parse(json);

and IMHO you posted an invalid json, it needs "{" before "AC Milan". So it should be like this

[
  {
    "Italy": [
      {
        "SerieA": [
          {
            "ACMilan": [
              {
                "Name": "Player1",
                "Goals": 3
              },
              {
                "Name": "Player2",
                "Goals": 5
              }
            ]
          }
        ]
      }
    ]
  }
]

in this case you can use this query

List<Score>  milanPlayersList = JArray.Parse(json)
.Select(i=> ((JObject) i).Properties().FirstOrDefault(x => x.Name=="Italy" ).Value).First()
.Select(i=> ((JObject) i).Properties().FirstOrDefault(x => x.Name=="SerieA" ).Value).First()
.Select(i=> ((JObject) i).Properties().FirstOrDefault(x => x.Name=="ACMilan" ).Value).First()
.Select(i=>  i.ToObject<Score>()).ToList().Dump();

using this list you can make any kind of queries.

result

[
  {
    "Name": "Player1",
    "Goals": 3
  },
  {
    "Name": "Player2",
    "Goals": 5
  }
]

class

public class Score
{
    public string Name { get; set; }
    public int Goals {get; set;}
}

Upvotes: 3

Related Questions