Domanda

Ho bisogno di deserializzare alcuni JSON, ma il problema è che tutti i miei oggetti JSON non hanno lo stesso identico formato. Ecco un esempio del JSON che devo deseerializzare:

[
  {
    "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",
        }
      ]
    },
  }
 ]
.

Come puoi vedere, alcuni campi appaiono solo per alcuni oggetti ad esempio "Personal_honours". Ho bisogno di deserializzare il JSON in questa classe:

public class PlayerData
{
    public string Name { get; set; }
    public string BallonDor {get; set; }
    public string Information1{ get; set; }
    public string Country{ get; set; }
}
.

Io uso questo metodo che è veramente a lungo e blocca la mia app: (In questo esempio uso JSON che viene da un textfile ma di solito devo fare una richiesta di riposo ..)

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

                                });

                            }

                        }

                    }
.

Questo metodo funziona ma non è efficiente e blocca il mio UI. Come posso fare per creare un nuovo oggetto "PlayerData" senza avere tutte le dichiarazioni di "altro se"?
Grazie!

P.S: La domanda è diversa da questo Filtro JSON Information

Modifica:

Ecco come ho ottenuto il runtimeBinderexPecetion:

 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

        });
    }
.

È stato utile?

Soluzione

Hai un'eccezione perché alcuni dati non hanno proprietà Personal_Honours, ad esempio.Quindi hai provato a accedere alla proprietà Ballon_Dor da un riferimento di null che attiva l'eccezione.Questo modo funzionerà per il campione JSON hai pubblicato:

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
    });
}
.

... ma l'approccio sopra è ancora un errore incline a seconda di quanto sia coerente la stringa JSON che abbiamo.Un'approccio più robusto è forse per avere lezioni di modelli per mappare JSON String come suggerito da @ L.B in commento.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top