我无法从JArray获取数据,特别是我正在尝试访问ID值.这是一个
JSON示例
{ "page": 1,"totalPages": 5,"pageSize": 2,"sortField": "label","sortOrder": "asc","content": [ { "organizationId": "Org123","id": "333","label": "comp1" },{ "organizationId": "Org123","id": "444","label": "comp2" } ] }
这就是我在C#中所拥有的
JArray jArray = new JArray(jsonString); foreach (JValue item in jArray) { Console.WriteLine(item["id"]); }
我知道我需要检查JValue以确保它是一个ID类型,但是我对在JArray中分解后分配的对象类型感到困惑.
解决方法
首先,你要处理顶级对象.解析对象后,您需要查看内容数组:
var obj = JObject.Parse(json); foreach (JObject element in obj["content"]) { Console.WriteLine(element["id"]); }
这是一个例子:https://dotnetfiddle.net/DhVZFf
另外(这可能只是一个错字),你的JSON格式不正确.具体来说,内容数组中的逗号分隔元素位于错误的位置:
{ "organizationId": "Org123","label": "comp1",// <--- } { "organizationId": "Org123","label": "comp2",}
那些逗号应该在数组元素之间:
{ "organizationId": "Org123","label": "comp1" },// <--- { "organizationId": "Org123","label": "comp2" }