gpt4 book ai didi

c# - 将嵌套的 JSON 转换为简单的 JSON

转载 作者:太空狗 更新时间:2023-10-29 22:25:34 25 4
gpt4 key购买 nike

我正在尝试通过递归遍历将嵌套的 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<JObject>().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<JObject>().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);

关于c# - 将嵌套的 JSON 转换为简单的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41692991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com