动态选择所需的JSON信息
本文关键字:JSON 信息 选择 动态 | 更新日期: 2023-09-27 18:15:12
我需要反序列化一些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_honors"。我需要将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:这个问题和这个不一样,过滤JSon信息
编辑:
下面是我如何得到runtimebinderexception:
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
});
}
你得到例外,因为一些数据没有Personal_Honours
属性,例如。然后您尝试从触发异常的null
引用访问Ballon_Dor
属性。这种方式将适用于您发布的示例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所建议的那样。