2017-10-04 133 views
0

我正在編寫一個工具,它將接收入站Json對象,並將其轉換爲 鍵值記錄(有時也稱爲展平,也許)。其目的是避免工具被破壞,如果它獲得非常大或非常嵌套的Json對象,所以我想避免遞歸。C#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類導入。只是重新迭代,理想的解決方案不會涉及遞歸,因爲吹堆棧會很糟糕。感謝任何即將到來的幫助。

+2

會Nuget包newtonsoft json的幫助?聽起來像他們已經爲你寫了你的工具https://www.newtonsoft.com/json –

+0

如果你在你的JSON遞歸中吹你的堆棧,我會說JSON比你吹的堆棧更糟糕。無論如何,我沒有在你的問題中看到任何代碼,也沒有說明你自己做了什麼,並且感覺你要求我們給你寫一段代碼... – oerkelens

+0

@ Aaron.S - 是的,使用它。我將字符串轉換爲動態對象,但對象結構未知,所以問題是如何訪問動態json對象的每個節點。感謝這篇文章。 –

回答

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路徑。

+1

這是完美的!爲了幫助那些來這裏尋找完整答案的人,我不得不爲Newtonsoft.Json.Linq和System.Linq添加使用語句。我還必須使用Regex.Replace(key,「\\ [(\\ d +)\\]」,分隔符+「$ 1」);刪除括號,並用簡單的字符串替換「。」用於分隔符,其中分隔符是用戶選擇的正斜槓字符。很好的回答,非常感謝,希望它也能幫助其他人。 –