使用Json.NET序列化子类 [英] Serialize subclass with Json.NET

查看:285
本文介绍了使用Json.NET序列化子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Json.NET序列化一个子类.生成的json包含超类的序列化属性,但子类对象的属性.

I am trying to use Json.NET to serialize a subclass. The resulting json contains the serialized properties for the superclass but not the properties on the subclass object.

这似乎与我在SO上的此处找到的问题有关.但是必须写JsonConverter似乎有点过分.

This seems to be related to an issue I found here on SO. But having to write a JsonConverter seems like overkill.

示例子类:

public class MySubclass : List<string>
{
    public string Name { get; set; }
}

序列化示例:

MySubclass myType = new MySubclass() { Name = "Awesome Subclass" };
myType.Add("I am an item in the list");

string json = JsonConvert.SerializeObject(myType, Newtonsoft.Json.Formatting.Indented);

生成的json:

[
  "I am an item in the list"
]

我希望结果会更像这样:

I expected to result to be more like this:

{
    "Name": "Awesome Subclass",
    "Items": [
        "I am an item in the list"
    ]
}

也许我只是在序列化时没有使用正确的配置.有人有建议吗?

Perhaps I am just not using the right configuration when serializing. Anyone have any suggestions?

推荐答案

根据文档:

.NET列表(继承自IEnumerable的类型)和.NET数组是 转换为JSON数组.由于JSON数组仅支持以下范围 值而不是属性,任何其他属性和字段 在.NET集合中声明的声明未序列化.

.NET lists (types that inherit from IEnumerable) and .NET arrays are converted to JSON arrays. Because JSON arrays only support a range of values and not properties, any additional properties and fields declared on .NET collections are not serialized.

因此,请勿继承List<T>的子类,只需添加第二个属性即可.

So, don't subclass List<T>, just add a second property.

public class MyClass 
{
    public List<string> Items { get; set; }
    public string Name { get; set; }

    public MyClass() { Items = new List<string>(); }
}

这篇关于使用Json.NET序列化子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆