user6906113
user6906113

Reputation:

Unable to parse the JSON When same name exist multiple times

I am parsing the JSON to extract the name details.But, I am getting an error. Could you please help me to extract the name details.

var jsonResult = JObject.Parse(jsonFileContents);
Console.WriteLine("Name :" + jsonResult["Name"]);

jsonFileContents:

[
  {
    "Name": "Joe",
    "Age": 25,
    "Rank": 1
  },
  {
    "Name": "Peter",
    "Age": 32,
    "Rank": 2
  }
]

Error: Unhandled Exception: Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item

Upvotes: 1

Views: 623

Answers (2)

Subburaj
Subburaj

Reputation: 2334

It looks, your input JSON is JSON Array. It needs to be parsed as below

You need to specify the Index to extract the respective elements. for example, To extract the first name.

var jsonResult = JArray.Parse(jsonFileContents);
Console.WriteLine("Name :" + jsonResult[0]["Name"]);

If you want to extract all the name details, then you can iterate and get it as below

Extract all the name Details from JSON Array:

       var jsonResult = JArray.Parse(jsonFileContents);
       for(int i = 0; i < jsonResult.Count; i++)
        {
            Console.WriteLine(jsonResult[i]["Name"]);
        }

Upvotes: 3

Shyam Joshi
Shyam Joshi

Reputation: 417

You have to look at the structure of the json object

It’s jsonobject >index array of objects > each object contains the name age

So getting first object will be like jsonresult[0][“Name”]

Upvotes: 1

Related Questions