简体   繁体   中英

C# Json Convert any dynamic object to key value pairs

I am writing a tool that will take an inbound Json object, and convert it to key-value records (sometimes called flattening, maybe). The aim is to avoid the tool breaking if it gets a very large or very nested Json object, so I would like to avoid recursion.

An example object might be like this (below), containing nested arrays, empty values, you name it, literally any legal 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
}

The desired output for the object above would be a key-value pair for every element of the object...

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

I have the example object above in memory as a dynamic object, imported using Newtonsoft's JSON class. Just to re-iterate, the ideal solution would not involve recursion, as a blown stack would be bad. Thanks for any help forthcoming.

Try this:

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);

It gives you:

[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, ]

I believe you will be able to make Replace in the path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM