如何遍历json数组

问题描述 投票:-3回答:1

我们如何迭代Map数组?

我的有效载荷看起来像这样:

{
  "Record": "...bunch of hl7 data...",
  "Map": [{ "DG1.2": "PatientDiag1" }, { "DG1.3": "PatientDiag2" }]
}

我们如何迭代和解析Map数组的值?

我尝试了以下操作:

var blobObject = JObject.Parse(blob); 
var map = blobObject["Map"];  //it's a JToken at this point
//now let's parse each key/value pair in the map:
foreach (var field in map)
{

    var key = field.ToString();
    var value = field[0].Value
}
c# .net json.net
1个回答
0
投票

"Map"JSON对象数组,因此首先需要遍历该数组,然后可以遍历每个对象的键/值对:

var blobObject = JObject.Parse(blob); 
var map = blobObject["Map"];  //it's a JToken at this point
//now let's parse each key/value pair in the map:
foreach (var item in map.Cast<JObject>()) //  Map is an array of objects so loop through the array, then loop through the key/value pairs of each object
{
    foreach (var pair in item)
    {
        var key = pair.Key;
        var value = pair.Value;
    }
}           

或者,如果您希望使用LINQ的SelectMany()来使数组变平:

SelectMany()

注意:

  1. 来自foreach (var pair in map.Cast<JObject>().SelectMany(o => (IDictionary<string, JToken>)o)) { var key = pair.Key; var value = pair.Value; }

    JSON建立在两个结构上:

    • 名称/值对的集合。在各种语言中,这是作为对象,记录,结构,字典,哈希表,键列表或关联数组实现的。
    • 值的有序列表。在大多数语言中,这是通过数组,向量,列表或序列来实现的。

    [JSON数组映射到JSON spec,而JSON对象映射到JArray

  2. 我们如何...解析Map数组的值?您不需要parse JArray数组的值,它们已经被完全解析。您只需要使用JObject来查询它们。

演示小提琴JObject

© www.soinside.com 2019 - 2024. All rights reserved.