Last active
April 8, 2016 17:50
-
-
Save TerribleDev/03bc02e064623fe634a1e70664ea225e to your computer and use it in GitHub Desktop.
ILookup serializer for json.net
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
public class LookupSerializer | |
{ | |
public static LookupSerializer<Key, Value> New<Key, Value>(ILookup<Key,Value> lookup) | |
{ | |
return new LookupSerializer<Key, Value>(); | |
} | |
} | |
public class LookupSerializer<Key, Value> : JsonConverter | |
{ | |
public override bool CanConvert(Type objectType) | |
{ | |
var result = objectType.GetInterfaces() | |
.Any(a => a.IsGenericType && a == typeof(ILookup<Key, Value>)); | |
return result; | |
} | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
throw new NotImplementedException(); | |
} | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
var target = value as ILookup<Key, Value>; | |
var obj = new JObject(); | |
var keys = target | |
.Select(a => a.Key) | |
.Distinct(); | |
foreach(var key in keys) | |
{ | |
obj.Add(key.ToString(), JArray.FromObject(target[key])); | |
} | |
obj.WriteTo(writer); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use this like
LookupSerializer.New(YourILookupHere)
or you can donew LookupSerializer<YourILookupKey, YourILookupValue>();
and then pass it into Newtonsoft.Json aka Json.Net as a custom serializer