我正在尝试通过递归遍历将嵌套json转换为简单json。(输入json的结构未知)
例如,我想要这样的json
{ "FirstName": "Rahul", "LastName": "B", "EmpType": { "RID": 2, "Title": "Full Time" }, "CTC": "3.5", "Exp": "1", "ComplexObj": { "RID": 3, "Title": { "Test": "RID", "TWO": { "Test": 12 } } } }
被转换成这样
{ "FirstName": "Rahul", "LastName": "B", "EmpType__RID": 2, "EmpType__Title": "Full Time", "CTC": "3.5", "Exp": "1", "ComplexObj__RID": 3, "ComplexObj__Title__Test": "RID", "ComplexObj__Title__TWO__Test": 12 }
嵌套对象中的每个字段都将更改为代表其实际路径的键。
这是我到目前为止所做的。
public static void ConvertNestedJsonToSimpleJson(JObject jobject, ref JObject jobjectRef, string currentNodeName = "", string rootPath = "") { string propName = ""; if (currentNodeName.Equals(rootPath)) { propName = currentNodeName; } else { propName = (rootPath == "" && currentNodeName == "") ? rootPath + "" + currentNodeName : rootPath + "__" + currentNodeName; } foreach (JProperty jprop in jobject.Properties()) { if (jprop.Children().Count() == 0) { jobjectRef.Add(propName == "" ? jprop.Name : propName + "__" + jprop.Name, jprop.Value); } else { currentNodeName = jprop.Name; rootPath = rootPath == "" ? jprop.Name : rootPath; ConvertNestedJsonToSimpleJson(JObject.Parse(jprop.Value.ToString()), ref jobjectRef, currentNodeName, rootPath); } } }
并得到错误的结果
{ "FirstName": "Rahul", "LastName": "B", "EmpType__RID": 2, "EmpType__Title": "Full Time", "CTC": "3.5", "Exp": "1", "EmpType__ComplexObj__RID": 3, "EmpType__Title__Test": "RID", "EmpType__two__Test": 12 }
将感谢您提供有关纠正我的代码的帮助,或任何其他存档方法。
您无需将属性的值转换为字符串,然后每次都再次解析-只需将其转换为 JObject
您不需要复杂的条件逻辑来生成属性的名称-只需使用以下命令: prefix + jprop.Name + "__"
代码:
public static void FlattenJson(JObject node, JObject result, string prefix = "") { foreach (var jprop in node.Properties()) { if (jprop.Children().Count() == 0) { result.Add(prefix + jprop.Name, jprop.Value); } else { FlattenJson((JObject)jprop.Value, $"{prefix}{jprop.Name}__", result); } } }
您可以这样称呼它:
var node = JObject.Parse(/* the input string */); var result = new JObject(); FlattenJson(node, result);