C#Json将任何动态对象转换为键值对 [英] C# Json Convert any dynamic object to key value pairs
问题描述
我正在编写一个工具,它将接收入站Json对象,并将其转换为 键值记录(有时称为拼合).目的是避免在工具变得很大或嵌套的Json对象时导致工具损坏,因此我想避免递归.
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.
一个示例对象可能像这样(如下),包含嵌套数组,空值,您可以将其命名,实际上是任何合法的json ...
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
我在上面的示例对象中有一个动态对象,它是使用Newtonsoft的JSON类导入的动态对象.仅重申一下,理想的解决方案将不涉及递归,因为吹散的堆栈会很不好.感谢您的任何帮助.
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.
推荐答案
尝试一下:
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
.
I believe you will be able to make Replace
in the path.
这篇关于C#Json将任何动态对象转换为键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!