JSON反序列化:如何从对象的JSON数组中获取值 [英] JSON Deserialization: How to get values out of a JSON array of objects
问题描述
我已经在C#中成功反序列化了此JSON字符串,但是无法从嵌套在数组中的对象中提取值:
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"]或_members [0] .name
_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...
推荐答案
我建议使用 Json.NET 来完成您的工作正在做.以下代码可以满足您的要求:
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
通过 LINQ to Json .
更新:
var js = new JavaScriptSerializer();
var d = js.Deserialize<dynamic>(json);
Console.WriteLine(d["members"][0]["name"]); // Joe
也可以.
这篇关于JSON反序列化:如何从对象的JSON数组中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!