C#Json将任何动态对象转换为键值对

时间:2017-10-04 16:07:16

标签: c# json dynamic json.net

我正在编写一个工具,它将获取入站Json对象,并将其转换为 键值记录(有时也称为展平)。目的是避免工具破坏,如果它得到一个非常大或非常嵌套的Json对象,所以我想避免递归。

一个示例对象可能是这样的(下面),包含嵌套数组,空值,你命名它,字面意思是任何合法的json ......

{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "office",
      "number": "646 555-4567"
    },
    {
      "type": "mobile",
      "number": "123 456-7890"
    }
  ],
  "children": [],
  "spouse": null
}

上述对象的所需输出将是对象的每个元素的键值对...

Key                     Value
/firstName              "John"
/lastName               "Smith"
/isAlive                "true"
/age                    "25"
/address
/address/streetAddress  "21 2nd Street"
/address/city           "New York"
/address/state          "NY"
/address/postalCode     "10021-3100"
/phoneNumbers
/phoneNumbers/1/
/phoneNumbers/1/type    "home"
/phoneNumbers/1/number  "212 555-1234"
/phoneNumbers/2/
/phoneNumbers/2/type    "office"
/phoneNumbers/2/number  "646 555-4567"
/phoneNumbers/3/
/phoneNumbers/3/type    "mobile"
/phoneNumbers/3/number  "123 456-7890"
/children
/spouse

我将上面的示例对象作为动态对象在内存中使用Newtonsoft的JSON类导入。只是为了重新迭代,理想的解决方案不会涉及递归,因为一个爆炸的堆栈会很糟糕。感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:2)

试试这个:

var json = File.ReadAllText("test.txt");
var obj = JObject.Parse(json);

var result = obj.Descendants()
    .OfType<JProperty>()
    .Select(p => new KeyValuePair<string, object>(p.Path,
        p.Value.Type == JTokenType.Array || p.Value.Type == JTokenType.Object
            ? null : p.Value));

foreach (var kvp in result)
    Console.WriteLine(kvp);

它给你:

[firstName, John]
[lastName, Smith]
[isAlive, True]
[age, 25]
[address, ]
[address.streetAddress, 21 2nd Street]
[address.city, New York]
[address.state, NY]
[address.postalCode, 10021-3100]
[phoneNumbers, ]
[phoneNumbers[0].type, home]
[phoneNumbers[0].number, 212 555-1234]
[phoneNumbers[1].type, office]
[phoneNumbers[1].number, 646 555-4567]
[phoneNumbers[2].type, mobile]
[phoneNumbers[2].number, 123 456-7890]
[children, ]
[spouse, ]

我相信你可以在路径上Replace