Home > Software design >  Serialize and deserialize json c#
Serialize and deserialize json c#

Time:08-24

I'm trying to build a json (with success) but now i need to deserialize the json, it's the first time i'm using json so i don't really know what do to. I got that's exception when i try to deserialize:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,Boosty.AltsInfos[]]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '', line 1, position 1.

  • Serializer:

    var json = new List<Alts>();
    List<AltsInfos> p1 = new List<AltsInfos> { new AltsInfos { alts_name = "JeSaisPas", alts_email = "[email protected]", alts_pass = "azerty", alts_type = AltsInfos.AltType.Microsoft } };
              json.Add(new Alts { account = p1 });
              List<AltsInfos> p2 = new List<AltsInfos> { new AltsInfos { alts_name = "TrucBidule", alts_email = "[email protected]", alts_pass = "azerty2.0", alts_type = AltsInfos.AltType.Microsoft } };
              json.Add(new Alts { account = p2 });
    
              string jsonString = JsonConvert.SerializeObject(json, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented });
              File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)   @"/BoostyLauncher"   @"/alts.json", jsonString);
    
  • Deserializer

              using (StreamReader sr = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)   @"/BoostyLauncher"   @"/alts.json"))
              {
                  string json = sr.ReadToEnd();
                  List<AltsInfos> alts = JsonConvert.DeserializeObject<List<AltsInfos>>(json);
                  foreach (var item in alts)
                      Console.WriteLine(item.alts_email);
     }
    
  • Type containers

    class Alts
    {
      public List<AltsInfos> account { get; set; }
    }
     class AltsInfos
     {
      public string alts_name { get; set; }
      public string alts_email { get; set; }
      public string alts_pass { get; set; }
      public AltType alts_type { get; set; }
    
      public enum AltType
      {
          [EnumMember(Value = "Microsoft")]
          Microsoft,
          [EnumMember(Value = "Altening")]
          Altening
      }
    }
    

All i want is to extract alts_name for each account category. Also i don't know how i set the enum in the json it's set to 0.

[
  {
    "account": [
      {
        "alts_name": "JeSaisPas",
        "alts_email": "[email protected]",
        "alts_pass": "azerty",
        "alts_type": 0
      }
    ]
  },
  {
    "account": [
      {
        "alts_name": "TrucBidule",
        "alts_email": "[email protected]",
        "alts_pass": "azerty2.0",
        "alts_type": 0
      }
    ]
  }
]

CodePudding user response:

You need to fix a bug in your deserialize code. Instead of List< AltsInfos > use List< Alts >

List<Alts> alts = JsonConvert.DeserializeObject<List<Alts>>(jsonString);

foreach (var alt in alts)
           foreach (var item in alt.account)
              Console.WriteLine(item.alts_email);

or you can use LINQ

List<string> emails = alts.SelectMany(a => a.account.Select(s => s.alts_email)).ToList();

and BTW if you want a json string to be indented, fix the serializer options too

string jsonString = JsonConvert.SerializeObject(json, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});

CodePudding user response:

I have made changes in deserialized line. should always deserialze into same class (which serialized into json) that is List< Alts >.

var json = new List<Alts>();
   List<AltsInfos> p1 = new List<AltsInfos> { new AltsInfos { alts_name = "JeSaisPas", alts_email = "[email protected]", alts_pass = "azerty", alts_type = AltType.Microsoft } };
   json.Add(new Alts { account = p1 });
   List<AltsInfos> p2 = new List<AltsInfos> { new AltsInfos { alts_name = "TrucBidule", alts_email = "[email protected]", alts_pass = "azerty2.0", alts_type = AltType.Microsoft } };
   json.Add(new Alts { account = p2 });

   string jsonString = JsonConvert.SerializeObject(json, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented });
   **List<Alts>** alts = JsonConvert.DeserializeObject<**List<Alts>**>(jsonString);

Please let me know if it solve your problem otherwise will try to explain more.

  • Related