简体   繁体   English

从JSON.net中的JArray中获取值

[英]Getting values out of a JArray in JSON.net

I am having trouble getting data from my JArray, specifically I am trying to access the ID value. 我无法从JArray获取数据,特别是我正在尝试访问ID值。 Here is a JSON example 这是一个JSON示例

{
"page": 1,
"totalPages": 5,
"pageSize": 2,
"sortField": "label",
"sortOrder": "asc",
"content": [
  {
  "organizationId": "Org123",
  "id": "333",
  "label": "comp1"
  },
  {
  "organizationId": "Org123",
  "id": "444",
  "label": "comp2"
  }
]
}

And here is what I have in C# 这就是我在C#中所拥有的

        JArray jArray = new JArray(jsonString);

        foreach (JValue item in jArray)
        {
            Console.WriteLine(item["id"]);
        } 

I know I need to check the JValue to make sure it is an ID type, but I am confused on object types assigned once it's broken down in the JArray. 我知道我需要检查JValue以确保它是一个ID类型,但是我对在JArray中分解后分配的对象类型感到困惑。

First off, you're dealing with an object at the top level. 首先,你要处理顶级对象。 After parsing the object, you need to look at the content array: 解析对象后,您需要查看content数组:

var obj = JObject.Parse(json);

foreach (JObject element in obj["content"])
{
    Console.WriteLine(element["id"]);
}

Here's an example : https://dotnetfiddle.net/DhVZFf 这是一个例子https//dotnetfiddle.net/DhVZFf

Also (and this might just be a typo), your JSON is malformed. 另外(这可能只是一个错字),你的JSON格式不正确。 Specifically, the comma separating elements in the content array are in the wrong place: 具体来说, content数组中的逗号分隔元素位于错误的位置:

{
    "organizationId": "Org123",
    "id": "333",
    "label": "comp1", // <---
}
{
  "organizationId": "Org123",
  "id": "444",
  "label": "comp2",
}

Those commas should be between array elements: 那些逗号应该数组元素之间

{
    "organizationId": "Org123",
    "id": "333",
    "label": "comp1"
}, // <---
{
  "organizationId": "Org123",
  "id": "444",
  "label": "comp2"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM