Seleccionar de forma dinámica Requiere JSON información
-
20-12-2019 - |
Pregunta
Necesito deserializar algunos JSON pero el problema es que todos mis objetos JSON no tienen exactamente el mismo formato.Aquí es un ejemplo de JSON que he deserializar :
[
{
"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",
}
]
},
}
]
Como se puede ver, algunos campos aparecen sólo para algunos objetos, por ejemplo, "Personal_Honours".Necesito deserializar el JSON en esta clase :
public class PlayerData
{
public string Name { get; set; }
public string BallonDor {get; set; }
public string Information1{ get; set; }
public string Country{ get; set; }
}
Yo uso este método que es muy larga y los bloques de mi app :(En este ejemplo yo uso Json que viene frome un archivo de texto, pero por lo general tengo que hacer un DESCANSO petición..)
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
});
}
}
}
Este método está trabajando, pero no es eficiente y bloques de mi interfaz de usuario.Cómo puedo hacer para crear un nuevo "PlayerData" objeto sin tener todos esos 'si por el contrario, las declaraciones ?
Gracias !
P. S :La cuestión es distinta a la de éste Filtro De JSon Información
EDITAR :
Aquí es cómo conseguí el 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
});
}
Solución
Tienes excepción debido a que algunos datos no tienen Personal_Honours
la propiedad, por ejemplo.A continuación, intenta tener acceso Ballon_Dor
la propiedad de una null
de referencia que dispara la excepción.Esta forma de trabajo para la muestra de JSON publicado :
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
});
}
...pero por encima de enfoque sigue siendo propensa a errores, dependiendo de cuán consistente es la cadena JSON que tenemos.Más sólido enfoque es tal vez tener clases del modelo de mapa de cadena JSON como sugerido por @L. B en el comentario.