[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.
According to the comments above (thanks!) there are two ways to get a correct result:
JsonConverter
(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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With