0

I'm trying to deserialize a collection of objects in JSON format, wich have a common parent class but when ServiceStack deserializes my request I get all the elements in my collection of the type of the parent class instead of each individual subclass. Is it possible to create a custom deserializer and avoid ServiceStack automatic deserialization.

Example:

class Canine {
    public Types Type { get; set; }
}

class Dog : Canine {
    public Dog() {
        Type = Types.Dog;
    }
}

class Wolf : Canine {
    public Wolf() {
        Type = Types.Wolf;
    }
}

public enum Types {
    Canino = 1,
    Perro = 2,
    Lobo = 3
}

public class CanineService : Service {
            public CanineResponse Post(Canine request) {
                return new Canine().GetResponse(request);
            }
        }

I'm deserializing this JSON with json.NET

    public class CanineConverter : JsonConverter {
    public override bool CanConvert(Type objectType) {
        return typeof(Canine).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
        var item = JObject.Load(reader);

        switch (item["Type"].Value<int>()) {
            case 2: return item.ToObject<Dog>();
            case 3: return item.ToObject<Wolf>();
        }

        return item["Type"].Value<Types>();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
        throw new NotImplementedException();
    }
}

1 Answers1

0

See this answer on why inheritance should avoided in DTO's as well as how to enable ServiceStack to retain type information which is only emit late-bound .NET type information for types that absolutely need it, i.e. Interfaces, late-bound object types or abstract classes.

The solution is to change the base-class of Canine to be an abstract type:

abstract class Canine
{
    public Types Type { get; set; }
}
Community
  • 1
  • 1
mythz
  • 141,670
  • 29
  • 246
  • 390
  • Thanks for your answer, in my particular case I think is better for me to stick with inheritance even though I have seen your link. My solution was created a custom deserializer for the types who needed it and created a new format for the requests in order to avoid ServiceStack from automatically deserilaze my DTO. – oscaregerardo Oct 08 '14 at 16:16
  • @oscaregerardo can you share your solution of how you created the new format for the request and how that's used along with the custom serializer ? – Niko Yakimov Jan 25 '22 at 19:25