c# - 遍历复杂的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
}}
解决方案
您需要稍微更改逻辑以读取子对象
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"]);
}
}
}
}
推荐阅读
- laravel - Laravel JSON 响应错误处理不起作用
- apache - 通过 .htaccess 从 URL 中删除双斜杠的问题
- typescript - 在嵌套对象中使用 firestore 的 FieldPath.documentId()
- javascript - React:在渲染函数中获取函数的返回值
- reactjs - 单击链接时滚动到页面一部分的React.js Header?
- python - 将数据框转换为列表时更改值
- c# - JsonSerializer.Deserialize 多次使用
- javascript - 根据 JSON Array 重新排列 HTML 表格数据
- javascript - 在 ^UNSAFE_ 方法的情况下如何忽略 eslint?
- msbuild - 如何在 Visual Studio 中找到包含文件的路径链?