Skip to content

Instantly share code, notes, and snippets.

@juanpaexpedite
Created January 19, 2019 20:01
Show Gist options
  • Save juanpaexpedite/2c11195b3462bd25ef5459a2a723efc9 to your computer and use it in GitHub Desktop.
Save juanpaexpedite/2c11195b3462bd25ef5459a2a723efc9 to your computer and use it in GitHub Desktop.
This class converts a list serialized into a Dictionary and when you serialize back goes to a List again
public class ListDictionaryConverter<T> : JsonConverter where T : Entity
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(object));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Dictionary<string, T> result;
if (reader.TokenType == JsonToken.StartArray)
{
result = new Dictionary<string, T>();
var token = JObject.ReadFrom(reader);
foreach(var value in token)
{
var item = value.ToObject<T>(serializer);
result.Add(item.Id, item);
}
}
else
{
result = (Dictionary<string, T>)serializer.Deserialize(reader, typeof(Dictionary<string, T>));
}
return result;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
List<T> list = new List<T>();
if (value is IDictionary dictionary)
{
foreach(var v in dictionary.Values)
{
list.Add((T)v);
}
serializer.Serialize(writer, list);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment