我正在编写一个将接入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类导入。仅仅是重新开始的,理想的解决方案就不会涉及递归,因为爆炸的堆栈将是不好的。感谢您的任何帮助。
尝试以下:
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
。