I'm using a JsonConverter to deal with a polymorphic collection:
class ItemBatch
{
List<ItemBase> Items { get; set; }
}
// For type discrimination of ItemBase
class ItemTypes
{
public int Value { get; set; }
}
[JsonConverter(typeof(ItemConverter))]
abstract class ItemBase
{
public abstract ItemTypes Type { get; set; }
}
class WideItem : ItemBase
{
public override ItemTypes Type => 1;
public decimal Width { get; set; }
}
class HighItem : ItemBase
{
public override ItemTypes Type => 2;
public decimal Height { get; set; }
}
class ItemConverter : JsonConverter<ItemBase>
{
public override ItemBase? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using (JsonDocument jsonDoc = JsonDocument.ParseValue(ref reader));
int type = jsonDoc.RootElement.GetProperty("Type").GetProperty("Value").GetInt32();
// deserialize depending on type.
}
}
Am using Blazor and store the ItemBatch in IndexedDb before retrieving again later and sending to WebAPI.
Serializing to IndexedDb and deserializing from IndexedDb works fine.
But, when I try to send the ItemBatch to a WebAPI, I get the error:
Exception thrown: 'System.Collections.Generic.KeyNotFoundException' in System.Text.Json.dll An exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in System.Text.Json.dll but was not handled in user code The given key was not present in the dictionary.
From peeking at various values, I suspected an issue with case-sensitivity. Indeed, if I change:
int type = jsonDoc.RootElement.GetProperty("Type").GetProperty("Value").GetInt32();
to
int type;
try
{
type = jsonDoc.RootElement.GetProperty("Type").GetProperty("Value").GetInt32();
}
catch (Exception)
{
type = jsonDoc.RootElement.GetProperty("type").GetProperty("value").GetInt32();
}
then I get past this error and my WebAPI gets called.
What am I missing that allows me to serialize / deserialize to / from IndexedDb, but the WebApi Json conversion is having issues with case sensitivity.