首页 > 解决方案 > 遍历复杂的json对象C#

问题描述

我收到以下格式的 JSON。而且我需要存储维护其与数据库关系的父子节点。

{
  "hour": {
    "Hour Access": {
      "labels": "Hour Access",
      "DisplayId": 2,
      "InputCodeValue": 1
    },
    "Hour": {
      "labels": "Hour",
      "DisplayId": 3,
      "InputCodeValue": 2
    },
    "DisplayId": 1
  },
  "patient": {
    "Doctor Patient": {
      "labels": "Doctor Patient",
      "DisplayId": 5,
      "InputCodeValue": 3
    },
    "Patient Portal": {
      "labels": "Patient Portal",
      "DisplayId": 6,
      "InputCodeValue": 4
    },
    "Patient Transportation": {
      "labels": "Patient Transportation",
      "DisplayId": 7,
      "InputCodeValue": 5
    },
    "Patient": {
      "labels": "Patient",
      "DisplayId": 8,
      "InputCodeValue": 6
    },
    "DisplayId": 4
  }
}

为了实现结果,我需要遍历 JSON。到目前为止,我已经尝试过:

JObject jObj = (JObject)JsonConvert.DeserializeObject(prod.ToString());
            foreach (var level1 in jObj)
            {
                var jObjKey = level1.Key;
                foreach (var level2 in level1.Value)
                {
                    //JObject finalLoop = (JObject)JsonConvert.DeserializeObject(level2.ToString());//Error
                }
            }

在 level2 中,我得到了无法迭代以获取该值的值。

2级:

{"Hour Access": {
  "labels": "Hour Access",
  "DisplayId": 2,
  "InputCodeValue": 1
}}

在此处输入图像描述

标签: c#json

解决方案


您需要稍微更改逻辑以读取子对象

JObject jObj = (JObject)JsonConvert.DeserializeObject(jsonString.ToString());
foreach (var level1 in jObj)
{
    var jObjKey = level1.Key;

    //get the final loop here before foreach
    JObject finalLoop = (JObject)JsonConvert.DeserializeObject(level1.Value.ToString());
    foreach (var level2 in finalLoop)
    {
        //check whether the level2 have keyvaluepair
        if (level2.Value.Count()>1)
        {
            //push the keyvaluepair to dictionary or dynamic object
            Dictionary<string, object> dictObj = JsonConvert.DeserializeObject<Dictionary<string, object>>(level2.Value.ToString());
            if (dictObj.Keys.Contains("labels"))
            { 
                Console.WriteLine(dictObj["labels"]);
            }
        }
    }
}

推荐阅读