Infinite conversion loop when using custom JsonConverter
Another way is to use serializer.Populate()
:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject item = JObject.Load(reader);
switch (item["type"].Value<string>())
{
case "Armor":
var armorItem = new ArmorItem();
serializer.Populate(item.CreateReader(), armorItem);
return armorItem;
default:
var defaultItem = new Item();
serializer.Populate(item.CreateReader(), defaultItem);
return defaultItem;
}
}
More infos at https://gist.github.com/chrisoldwood/b604d69543a5fe5896a94409058c7a95
In short, you need to tell Json.net to deserialize your json via standard converter, not your custom one. While there's more than one way to do it, this is the one I can offer right now:
Remove
JsonConverter(typeof(ItemConverter))
fromItem
. This will allowitem.ToObject<Item>()
to work properly.Now you need to tell your outer deserialization to use the converter. To do that:
var settings = new JsonSerializerSettings() { Converters = new [] { new ItemConverter() } }; return JsonSerializer.Create(settings).Deserialize<Item>(reader)
(actually, you can cache the settings)