Serialize subclass with Json.NET

时间秒杀一切 提交于 2019-12-09 16:39:41

问题


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.

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

Sample subclass:

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

Sample of the serialization:

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);

Resulting 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?


回答1:


According the documentation:

.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.

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>(); }
}



回答2:


Here are my thoughts on this. I would think that your expected results would be more consistent with a class like this:

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

I would not expect to see an Items element in the serialized result for MySubclass : List<string> since there is no Items property on List nor on MySubclass.

Since your class MySubclass is actually a list of strings, I would guess (and I am just guessing here) that the SerializeObject method is merely iterating through your object and serializing a list of strings.



来源:https://stackoverflow.com/questions/11367796/serialize-subclass-with-json-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!