遍历复杂的json对象C#

时间:2019-09-27 12:02:12

标签: c# json

我正在接收以下格式的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中,我获得了无法迭代以获取值的值。

level2:

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

enter image description here

1 个答案:

答案 0 :(得分:0)

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

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"]);
            }
        }
    }
}