Illep
Illep

Reputation: 16851

Read from unknown json structure - beginner

I have a JSON string, and I need to extract values from it- for example I need to get the value for ID and Name.

string someJson = @"[ {'ID': '12'} , { 'Name' : 'JAMES'} ]"; 

Note: I don't have a model created for this JSON.

My code:

string someJson = @"[ {'ID': '12'} , { 'Name' : 'JAMES'} ]"; 

List<object> json = JsonConvert.DeserializeObject<List<object>>(someJson);


Console.WriteLine("json count ", json[0]["ID"]);

The console.write doesn't print ID or can print Name. How can I solve this ? I hope I explained the question well, Sorry I am a newbie.

Upvotes: 0

Views: 442

Answers (2)

Martin Meeser
Martin Meeser

Reputation: 2956

Parse to a List<Dictionary<string, object>>

Check this example from JSON.NET.

Your example would look like this:

string someJson = @"[ {'ID': '12'} , { 'Name' : 'JAMES'} ]";
List<Dictionary<string, string>> student = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(someJson );
object val = student[0]["ID"];
Console.WriteLine($"json count {val.ToString()}");

Upvotes: 1

Kevin Smith
Kevin Smith

Reputation: 14456

You could use deserialize into a JArray

    string someJson = @"[ {'ID': '12'} , { 'Name' : 'JAMES'} ]"; 

    var json = JsonConvert.DeserializeObject<JArray>(someJson);

    Console.WriteLine("json count " + json[0]["ID"]);

Upvotes: 1

Related Questions