Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize object when the object inherits from list

[DataContract]
public class A : List<B>
{
    [DataMember]
    public double TestA { get; set; }
}

[DataContract]
public class B
{
    [DataMember]
    public double TestB { get; set; }
}

With the model above I try to serialize the following object:

List<A> list = new List<A>()
{
    new A() { TestA = 1 },
    new A() { TestA = 3 }
};

json = JsonConvert.SerializeObject(list);
//json: [[],[]]

Where are my two values from TestA? It's possible duplicate from this thread (XML), but I want to know if there is no option to include those values by setting some JSON serialize option?

Note: Creating a property List<B> in class A instead of inheritance is no option for me.

like image 207
gogcam Avatar asked Oct 31 '22 04:10

gogcam


1 Answers

According to the comments above (thanks!) there are two ways to get a correct result:

  • Implementing a custom JsonConverter (see here)
  • Workarround: Create a property in the class which returns the items (see here)

Anyway, inherit from List<T> is rare to be a good solution (see here)

I've tried it with the workarround:

[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class A : List<B>
{
    [JsonProperty]
    public double TestA { get; set; }

    [JsonProperty]
    public B[] Items
    {
        get
        {
            return this.ToArray();
        }
        set
        {
            if (value != null)
                this.AddRange(value);
        }
    }
}

public class B
{
    public double TestB { get; set; }
}

This works for serialization and deserialization. Important: Items must be an Array of B and no List<B>. Otherwise deserialization doesn't work for Items.

like image 153
gogcam Avatar answered Nov 09 '22 16:11

gogcam