Dynamic Deserialization using JsonConverter

This post is the continuation from the previous post. The previous post was in regard to casting the object dynamically. This post will explain how to deserialize dynamically from Json object

I have a json that I want to deserialize dynamically based on a specific property that defines what object it is. We can do it easily and elegantly by using JsonConverter

1. Create a custom JsonConverter

public class MessageConverter : JsonConverter
        static readonly JsonSerializerSettings SpecifiedSubclassConversion = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() };

        public override bool CanConvert(Type objectType)
            return (objectType == typeof(WhafflMetadata));

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

            switch (jObject["messageType"].Value<string>())
                case "STAFF_CREATED":
                    return JsonConvert.DeserializeObject<Message<StaffDetail>>(jObject.ToString(), SpecifiedSubclassConversion);

                case "CITY_CREATED":
                    return JsonConvert.DeserializeObject<Message<City>>(jObject.ToString(), SpecifiedSubclassConversion);

                    throw new Exception(string.Format("messageType {0} cannot be handled", jObject["messageType"].Value<string>()));

        public override bool CanWrite
            get { return false; }

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

2. Cast it using your converter

                new JsonSerializerSettings { Converters = new JsonConverter[] { new MessageConverter() } });

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s