【问题标题】:Cannot serialize inherited property into JSON via Json.Net无法通过 Json.Net 将继承的属性序列化为 JSON
【发布时间】:2012-11-28 20:13:42
【问题描述】:

我正在使用 C# .NET 4.0 和 Newtonsoft JSON 4.5.0.11

    [JsonObject(MemberSerialization.OptIn)]
    public interface IProduct
    {
        [JsonProperty(PropertyName = "ProductId")]
        int Id { get; set; }
        [JsonProperty]
        string Name { get; set; }
    }

    public abstract class BaseEntity<T>
    {
        private object _id;

        public T Id
        {
            get { return (T)_id; }
            set { _id = value; }
        }
    }

    public class Product : BaseEntity<int>, IProduct
    {
        public string Name { get; set; }
        public int Quantity { get; set; }
    }

我需要序列化对象的一部分,并使用带有已声明具体属性的接口来执行此操作。

序列化如下:

Product product = new Product { Id = 1, Name = "My Product", Quantity = 5};
JsonConvert.SerializeObject(product);

预期结果是:

{"ProductId": 1, "Name": "My Product"}

但实际结果是:

{"Name": "My Product"}

如何正确序列化这个对象?


UPD:查看了json.net的源码,得出的结论是这是一个通过ReflectionUtils抓取对象信息的bug。

【问题讨论】:

    标签: c#-4.0 inheritance serialization json.net


    【解决方案1】:

    你试过了吗?

    public interface IProduct
    {
        int Id { get; set; }
        string Name { get; set; }
    }
    
    [JsonObject(MemberSerialization.OptIn)]
    public abstract class BaseEntity<T>
    {
        private object _id;
        [JsonProperty]
        public T Id
        {
            get { return (T)_id; }
            set { _id = value; }
        }
    }
    
    [JsonObject(MemberSerialization.OptIn)]
    public class Product : BaseEntity<int>, IProduct
    {
        [JsonProperty]
        public string Name { get; set; }
        [JsonProperty]
        public int Quantity { get; set; }
    }
    

    【讨论】:

    • 我不想在基类中使用 JsonProperty 和 JsonObject,因为它放置在另一个项目(库)中,它没有引用 Newtonsoft JSON dll。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2013-07-09
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多