从JSON对象构建属性列表c#

时间:2017-07-18 12:15:45

标签: c# json json.net

我想构建包含json对象的属性路径的属性列表。

我不知道json的结构或可能存在的键。我在所有级别的密钥之后(不是那些密钥的值)。

 {
  "Primitive_1": "T1",
  "Object_L1": {
    "Object_L2": {
      "Object_L3": {
        "Object_L4": {
          "Object_L5": {
            "Object_L6": {
              "Array_L7": [
                {
                  "asdasdas": "SampleText1",
                  "WIDTH": "Width2"
                },
                {
                  "gh45gdfg": "SampleText2",
                  "WIDTH": "Width"
                }
              ],
              "12836hasvdkl": "SampleText3",
              "WIDTH": "Width"
            }
          }
        },
        "712bedfabsmdo98": "SampleText4",
        "WIDTH": "Width"
      }
    },
    "ALIAS_ID": 1
  },
  "Primitive_2": "T2",
  "Primitive_3": "T3",
  "Primitive_4": "T4"
}

期望的输出:

.Primitive_1 .Object_L1.Object_L2.Object_L3.Object_L4.Object_L5.Object_L6.Array_L7.0.asdasdas
.Object_L1.Object_L2.Object_L3.Object_L4.Object_L5.Object_L6.Array_L7.0.WIDTH
.Object_L1.Object_L2.Object_L3.Object_L4.Object_L5.Object_L6.Array_L7.1.gh45gdfg
.Object_L1.Object_L2.Object_L3.Object_L4.Object_L5.Object_L6.Array_L7.1.WIDTH
.Object_L1.Object_L2.Object_L3.Object_L4.Object_L5.Object_L6.12836hasvdkl
.Object_L1.Object_L2.Object_L3.Object_L4.Object_L5.Object_L6.WIDTH
.Object_L1.Object_L2.Object_L3.712bedfabsmdo98
.Object_L1.Object_L2.Object_L3.WIDTH
.Object_L1.ALIAS_ID
.Primitive_2
.Primitive_3
.Primitive_4

环顾四周,我已经到了对象的根节点。请参阅小提琴(https://dotnetfiddle.net/wIl1Qw

这似乎在JS中相对简单(http://jsfiddle.net/alteraki/bt3zc1wt/)我已经回顾了几个响应,我在c#中找不到响应这个问题的响应,而不知道使用的密钥(我不知道)知道)

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

树遍历算法本质上几乎总是递归的。

因此,以下功能可以满足您的需求:

private static IEnumerable<string> GetMembers(JToken jToken)
{
    var members = new List<string>();

    if (jToken is JObject)
    {
        var jObject = (JObject)jToken;

        foreach (var prop in jObject.Properties())
        {
            if (prop.Value is JValue)
            {
                members.Add(prop.Name);
            }
            else
            {
                members.AddRange(GetMembers(prop.Value).Select(member => prop.Name + "." + member));
            }
        }
    }
    else if (jToken is JArray)
    {
        var jArray = (JArray)jToken;

        for (var i = 0; i < jArray.Count; i++)
        {
            var token = jArray[i];

            members.AddRange(GetMembers(token).Select(member => i + "." + member));
        }
    }

    return members;
}

正在运行的代码示例here