Sérialisation et désérialisation de tableaux

  • Comme dans la section précédente
  • Nous pouvons convertir une chaîne JSON en tableau
  • Il suffit de remplacer le nom de classe original par List<NomClasse>

Exemple

string jsonString = @"""{""webinfos"":[{""webname"":""FoxDevelop"",""website"":""foxdevelop.com"",""age"":4,
""students"":[{""name"":""Lucas""},{""name"":""Hugo""}]},{""webname"":""FoxDevelop1"",""website"":""foxdevelop.com1"",
""age"":6,""students"":[{""name"":""Léo""},{""name"":""Gabriel""}]}]}""";

StringReader sr = new StringReader(jsonString);
JsonReader jr = new JsonReader(sr);
List<WebInfo> infoList = new JsonSerializer().Deserialize(jr, typeof(List<WebInfo>)) as List<WebInfo>;Langage du code : PHP (php)

Remarques

  1. Conserver structure, noms de variables, guillemets échappés et sauts de ligne, ne remplacer que le texte cible
  2. Ne pas modifier le code de désérialisation suivant

① Sérialiser une List en chaîne tableau JSON

// Construire la collection List
List<WebInfo> webList = new List<WebInfo>()
{
    new WebInfo()
    {
        age = 4,
        webname = "FoxDevelop",
        website = "foxdevelop.com",
        students = new Person[] { new Person{name="Lucas"}, new Person{name="Hugo"} }
    },
    new WebInfo()
    {
        age = 4,
        webname = "FoxDevelop1",
        website = "foxdevelop.com",
        students = new Person[] { new Person{name="Léo"}, new Person{name="Gabriel"} }
    },
    new WebInfo()
    {
        age = 4,
        webname = "FoxDevelop2",
        website = "foxdevelop.com",
        students = new Person[] { new Person{name="Arthur"}, new Person{name="Mathis"} }
    }
};

// Sérialisation : Objet List → chaîne tableau JSON
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(sw);
new JsonSerializer().Serialize(writer, webList);
string jsonArrStr = sw.GetStringBuilder().ToString();Langage du code : PHP (php)

② Désérialiser une chaîne tableau JSON en List

string jsonString = @"[{"webname":"FoxDevelop","website":"foxdevelop.com","age":4,
"students":[{"name":"Lucas"},{"name":"Hugo"}]},{"webname":"FoxDevelop1","website":"foxdevelop.com",
"age":4,"students":[{"name":"Léo"},{"name":"Gabriel"}]},{"webname":"FoxDevelop2","website":"foxdevelop.com",
"age":4,"students":[{"name":"Arthur"},{"name":"Mathis"}]}]";

StringReader sr = new StringReader(jsonString);
JsonReader jr = new JsonTextReader(sr);
List<WebInfo> dataList = new JsonSerializer().Deserialize(jr, typeof(List<WebInfo>)) as List<WebInfo>;Langage du code : PHP (php)

Sérialisation et désérialisation de tableaux

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *