我得到一個第三方的API回應,其中有幾個嵌套的屬性:
變數1。
變數1:
{<
"Property1": {
"Property2A": {
"Key1": "1",
"Key2": "2",
"Key3": "3"/span>
},
"Property2B": {
"Property3": {
"Key4": "A",
"Key5": "B",
"Key6": "C"、
"Property4": {}。
"Property5": {
"Property6": [/span>
{
"Key7": "1",
"Property7A": {}。
"X": "1"
},
"Property7B": {
"X": "2"
},
"Property7C": {
"X": "3"
}
},
{>
"Property7D": {
"X": "IneedThisString"
}
}
]
}
}
}
}
}
}
我只需要值"INeedThisString"。
我能夠達到屬性"X "的值。"INeedThisString"通過一個合適的模型結構(通過在Json檔案上映射模型而產生)和以下宣告,我能夠達到屬性的值:
Rootobject obj = JsonConvert.DeserializeObject<Rootobject> (MyJsonString)。
string result = obj.Property1.Property2B.Property3.Property4.Property5.Property6[1].Property7D.X。
我的問題是這樣的:
API有時會發布這種架構的變體,其中唯一的區別是,Property3宣告為一個陣列,例如:
變體2:
{
"Property1"/span>: {
"Property2A": {
"Key1": "1",
"Key2": "2",
"Key3": "3"。
},
"Property2B": {
"Property3": [ //<-----。
{
"Key4": "A",
"Key5": "B",
"Key6": "C",
"Property4": {
"Property5": {
"Property6": [
{
"Key7": "1",
"屬性7A": {
"X": "1": "X".
},
"Property7B": {
"X": "2": "X".
},
"Property7C": {
"X": "3": "X".
}
},
{
"Property7D": {
"X": "INeedThisString"。
}
}
]
}
}
}
] //<-----。
}
}
}
//<-----:為了說明問題,增加了2倍。
顯然,變體1和我目前的模型結構沒有將Property3宣告為陣列。
問題:
有什么優雅的方法來解決這個問題?在預處理中不觸及 Json(洗掉/替換)?
我是否應該實作另一組模型,并通過錯誤函式在這兩個模型集之間進行切換?請注意,屬性7A-7D中的鍵都是相同的:"X"。
uj5u.com熱心網友回復:
我目前的作業方案涵蓋了決議所需的另一組類,這是由于映射Json回應的變體2所導致的。
所有的類都通過使用指令using Newtonsoft.Json的Json頭檔案[JsonProperty("actual-string-shown-in-Json")]來裝飾。
兩個備選的JsonConvert函式被放在一個try-catch陳述句中:
string result;
try
{
Rootobject obj = JsonConvert.DeserializeObject<Rootobject>(MyJsonString)。
result = obj.Property1.Property2B.Property3.Property4.Property5.Property6[1].Property7D.X。
}
抓取。
{
AltRootobject obj = JsonConvert.DeserializeObject<AltRootobject>(MyJsonString)。
結果 = obj.AltProperty1.AltProperty.AltProperty[0].AltProperty.AltProperty5.AltProperty6[1].AltProperty7D.AltX。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/332279.html
標籤:
