C# Json Convert any dynamic object to key value pairs

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

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.

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!