Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Deserialization: How to get values out of a JSON array of objects

Tags:

json

c#

I've successfully deserialized this JSON string in C#, but can't extract the values from the objects nested in the array:

JavaScriptSerializer js = new JavaScriptSerializer();

string json = 
  {"key":"1234","status":"ok","members":
      [{"id":7,"name":"Joe"},
   {"id":2,"name":"Robert"},
   {"id":18,"name":"Tim"}
      ]
   }

var d = js.Deserialize < dynamic > (json);

string _key = d["key"]; // this works

Array _members = d["members"]; // this works, length = 3

But I'm having trouble extracting the values out of the objects by name, e.g, this isn't right, but essentially I want

_members[0]["name"] or, _members[0].name

I think the deserializer makes the objects inside the array dictionaries, but I think I'm clearing missing something...

like image 618
brnwdrng Avatar asked Nov 30 '22 03:11

brnwdrng


2 Answers

I recommend using Json.NET to do what you're doing. The following code does what you want:

    JObject jObject = JObject.Parse(json);
    JToken memberName = jObject["members"].First["name"];
    Console.WriteLine(memberName); // Joe

Via LINQ to Json.

Update:

    var js = new JavaScriptSerializer();
    var d = js.Deserialize<dynamic>(json);
    Console.WriteLine(d["members"][0]["name"]); // Joe

Also works fine.

like image 107
David Peden Avatar answered Dec 22 '22 01:12

David Peden


It's a bit late for an answer but I've been trying to figure this out and thought I should post somewhere what worked for me.

I wanted to use foreach so:

foreach (var member in json["members"])
    {
        Console.WriteLine(member["name"]);
    }

and by the way, (for some reason like in my project) if you have nested arrays, e.g.

string json = 
{"key":"1234","status":"ok",
 "members":[
   {"items"[
       {"id":7,"name":"Joe"},
       {"id":2,"name":"Robert"},
       {"id":18,"name":"Tim"}
   ]}
]}

Then:

foreach (var member in json["members"])
    {
        foreach (var item in member["items"])
        {  
            Console.WriteLine(item["name"]);
        }
    }
like image 31
koko Avatar answered Dec 22 '22 00:12

koko