Created
February 9, 2018 20:29
-
-
Save mlienau/33cdfcfb44b53eeaab5109179ada5c1d to your computer and use it in GitHub Desktop.
JSON.NET converter for serializing a C# Dictionary to a javascript Map initialization array
This file contains hidden or 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
public class DictionaryToMapConverter<TKey, TValue> : JsonConverter | |
{ | |
public override bool CanConvert(Type objectType) | |
{ | |
return false; | |
} | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
// I'm only using this for writing as of now | |
throw new NotImplementedException(); | |
} | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
if (value == null) | |
{ | |
writer.WriteToken(JsonToken.Null); | |
return; | |
} | |
var values = value as IEnumerable<KeyValuePair<TKey, TValue>>; | |
if (values == null) | |
{ | |
throw new ArgumentException("value was not a dictionary"); | |
} | |
writer.WriteToken(JsonToken.StartArray); | |
foreach (var kvp in values) | |
{ | |
writer.WriteToken(JsonToken.StartArray); | |
serializer.Serialize(writer, kvp.Key); | |
serializer.Serialize(writer, kvp.Value); | |
writer.WriteToken(JsonToken.EndArray); | |
} | |
writer.WriteToken(JsonToken.EndArray); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And here's how you'd use in a view model.
When serialized it will spit out an array of key value pair arrays i.e
That way you can pass this array right into your map initializer