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...
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.
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"]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With