Search code examples
c#jsonconvert

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.


Solution

  • 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()}");