必要なJSON情報を動的に選択してください
-
20-12-2019 - |
質問
私はいくつかのJSONを逆シリアル化する必要がありますが、問題は私のJSONオブジェクトのすべてがまった同じフォーマットを持っていないということです。 これは私が逆シリアライズしなければならないJSONの例です:
[
{
"Player_Name": "Zlatan Ibrahimovic",
"Country": "Sweeden",
"Other_Informations": {
"Information1": [
]
},
},
{
"Player_Name": "Pavel Nedved",
"Country": "Czech Republic",
"Personal_Honours":
{
"Ballon_DOr": "One",
},
"Other_Informations": {
"Information1": [
]
},
},
{
"Player_Name": "Zinedine Zidane",
"Country": "Sweeden",
"Other_Informations": {
"Information1": [
{
"name": "example",
}
]
},
}
]
.
わかるように、いくつかのフィールドは「Personal_honours」などのオブジェクトのみに表示されます。 このクラスにJSONを逆シリアル化する必要があります。
public class PlayerData
{
public string Name { get; set; }
public string BallonDor {get; set; }
public string Information1{ get; set; }
public string Country{ get; set; }
}
.
本当に長い間私のアプリをブロックするこの方法を使用します。 (このexmpleでは、テキストファイルfrome frome jsonを使用していますが、通常はRESTリクエストを行わなければなりません..)
StreamReader reader = File.OpenText("TextFile1.txt");
List<PlayerData> DataList;
dynamic value= JsonConvert
.DeserializeObject<dynamic>(reader.ReadToEnd());
DataList = new List<PlayerData>();
foreach (dynamic data in value)
{
if (data.Personal_Honours == null)
{
if (data.Other_Informations.Information1 == null)
{
DataList.Add(new PlayerData
{
Name = data.Player_Name,
Country = data.Country,
});
}
else
{
DataList.Add(new PlayerData
{
Name = data.Player_Name,
Country = data.Country,
Information1 = data.Informations.Information1
});
}
}
else
{
if (data.Other_Informations.Information1 == null)
{
DataList.Add(new PlayerData
{
Name = data.Player_Name,
Country = data.Country,
BallonDor = data.Personal_Honours.Ballon_DOr
});
}
else
{
DataList.Add(new PlayerData
{
Name = data.Player_Name,
Country = data.Country,
BallonDor = data.Personal_Honours.Ballon_DOr,
Information1 = data.Informations.Information1
});
}
}
}
.
この方法は機能していますが、効率的ではなく、UIをブロックします。
「else」ステートメントのすべてを持たずに新しい「PlayerData」オブジェクトを作成するにはどうすればよいですか。
ありがとうございました!
P.S:この質問はこの1つとは異なる
解決
たとえば、DATAにはPersonal_Honours
プロパティがないため、例外が表示されます。次に、例外をトリガーするBallon_Dor
リファレンスからnull
プロパティにアクセスしようとしました。このようにしてあなたが投稿したサンプルJSONのために機能します:
List<PlayerData> datalist = new List<PlayerData>();
foreach (dynamic pl in timeline)
{
//object initialization is done later just for the sake of easier debugging
//...so we can spot unexpected data which cause exception easily
var Name = pl.Player_Name;
var Country = pl.Country;
var BallonDor = pl.Personal_Honours != null ? pl.Personal_Honours.Ballon_Dor : null;
var Information1 = pl.Other_Informations.Information1.Count > 0 ?
pl.Other_Informations.Information1[0].name :
null;
datalist.Add(new PlayerData
{
Name = Name ,
Country = Country ,
BallonDor = BallonDor,
Information1 = Information1
});
}
.
...しかし上記のアプローチは、JSON文字列がどれほど一貫しているかによって、まだエラーが発生しやすいです。もっと堅牢なアプローチは、コメントの@ L.Bによって提案されたようにJSON文字列をマッピングするためのモデルクラスを持つことができます。
所属していません StackOverflow