Deserialize to IEnumerable class using Newtonsoft Json.Net

后端 未结 1 1216
野的像风
野的像风 2021-01-03 22:48

I have a project that is currently using Json.Net for Json deserialization classes like these:

public class Foo {
    public Guid FooGuid { get; set; }
    p         


        
相关标签:
1条回答
  • 2021-01-03 23:14

    From the Json.Net documentation:

    IEnumerable, Lists and Arrays

    .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. In situations where a JSON array is not wanted the JsonObjectAttribute can be placed on a .NET type that implements IEnumerable to force the type to be serialized as a JSON object instead.

    In other words, since your class implements IEnumerable<T>, Json.Net thinks it is a list. To get around this, simply decorate your class with the [JsonObject] attribute. This will force Json.Net to serialize and deserialize it as a normal class, which is what you want in this case.

    [JsonObject]
    public class EnumerableFoo : IEnumerable<Bar>
    {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题