Home > Mobile >  Serializing a class with a list of variable does not restore it during deserialization but works for
Serializing a class with a list of variable does not restore it during deserialization but works for

Time:03-28

I am using Newtonsoft.Json to serialize a class and deserialize it for save/load functionality. However, I had some issues with doing it for a list of variables that does not occur when using a single variable. I have shown a minimum working example below:

Class to be saved:

public class C1
{
    public int a;

    public C1()
    {
        a = 123;
    }
}

public class RootClass
{
    public C1 single = new C1();
    public List<C1> list = new List<C1>() { new C1() };
}

Serializaing and Deserializaing:

    RootClass rc = new RootClass();
    rc.single.a = 789;
    rc.list[0].a = 789;

    Console.WriteLine(rc.single.a);
    Console.WriteLine(rc.list[0].a);

    string ToJason = JsonConvert.SerializeObject(rc);

    Console.WriteLine("-------");

    rc = JsonConvert.DeserializeObject<RootClass>(ToJason);

    Console.WriteLine(rc.single.a);
    Console.WriteLine(rc.list[0].a);

The printing result is:

789
789
-------
789
123

Which is not what I am looking for. I want rc.list[0].a to be 789 not 123, same as the other variable which was saved correctly.

Edit 1:

Here is the result of the serialization (JSON string)

{
  "single": {
    "a": 789
  },
  "list": [
    {
      "a": 789
    }
  ]
}

The issue is with the deserializing.

CodePudding user response:

To populate list in the constructor is not best idea, but you can workout like this

    var pd=JObject.Parse(ToJason);
    rc = pd.ToObject<RootClass>();
    rc.list=pd["list"].ToObject<List<C1>>();
  • Related