JSON Deserialization with an array of polymorphic objects

前端 未结 2 1084
长发绾君心
长发绾君心 2021-02-02 09:42

I\'m having a problem with JSON Deserialization involving an array of polymorphic objects. I\'ve tried the solutions for serialization documented here and here which work great

相关标签:
2条回答
  • 2021-02-02 09:49

    Use this JsonKnownTypes, similar way to do that:

    [JsonConverter(typeof(JsonKnownTypeConverter<BaseClass>))]
    [JsonKnownType(typeof(Base), "base")]
    [JsonKnownType(typeof(Derived), "derived")]
    public class Base
    {
        public string Name;
    }
    public class Derived : Base
    {
        public string Something;
    }
    

    Now when you serialize object in json will be add "$type" with "base" and "derived" value and it will be use for deserialize

    Serialized list example:

    [
        {"Name":"some name", "$type":"base"},
        {"Name":"some name", "Something":"something", "$type":"derived"}
    ]
    
    0 讨论(0)
  • 2021-02-02 09:56

    You have not added any settings upon deserialization. You need to apply settings with TypeNameHandling set to Object or All.

    Like this:

    JsonConvert.DeserializeObject(
        returnedStringFromClient, 
        typeof(Scoresheet), 
        new JsonSerializerSettings 
        { 
            TypeNameHandling = TypeNameHandling.Objects 
        });
    

    Documentation: TypeNameHandling setting

    0 讨论(0)
提交回复
热议问题