我需要反序列化一些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; }
}
我使用这个非常长的方法并阻止我的应用: (在这个例子中,我使用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。 如何创建一个新的“PlayerData”对象而不包含所有那些“else if”语句? 谢谢!
P.S:问题与此Filter JSon Information
不同编辑:
以下是我如何获得RunTimeBinderExcepetion:
List<PlayerData> datalist = new List<PlayerData>();
foreach (dynamic pl in timeline)
{
datalist.Add(new PlayerData
{
Name = pl.Player_Name ,
Country = pl.Country ,
BallonDor = pl.Personal_Honours.Ballon_Dor,
Information1 = pl.Other_Informations.Information1.name
});
}
答案 0 :(得分:0)
你有例外,因为有些数据没有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字符串的一致性。更强大的方法可能是让模型类映射JSON字符串,如@L.B在评论中所建议的那样。