简体   繁体   English

当对象从列表继承时序列化对象

[英]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 ? TestA中我的两个值在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? 这可能是从这个线程 (XML)重复,但我想知道是否没有选项通过设置一些JSON序列化选项来包含这些值?

Note: Creating a property List<B> in class A instead of inheritance is no option for me. 注意:在A类中创建属性List<B>而不是继承对我来说是没有选择的。

According to the comments above (thanks!) there are two ways to get a correct result: 根据上面的评论(谢谢!)有两种方法可以获得正确的结果:

  • Implementing a custom JsonConverter ( see here ) 实现自定义JsonConverter参见此处
  • Workarround: Create a property in the class which returns the items ( see here ) Workarround:在类中创建一个返回项的属性( 参见此处

Anyway, inherit from List<T> is rare to be a good solution ( see here ) 无论如何,从List<T>继承很少是一个很好的解决方案( 见这里

I've tried it with the workarround: 我已经尝试过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> . 要点: Items必须是BArray且没有List<B> Otherwise deserialization doesn't work for Items . 否则反序列化不适用于Items

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM