Last active
September 29, 2017 14:08
-
-
Save Flayed/855e6fadf34c1af63d47b59d00272e08 to your computer and use it in GitHub Desktop.
JsonConverter
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
| using System; | |
| using System.Collections.Generic; | |
| using Newtonsoft.Json; | |
| using Newtonsoft.Json.Linq; | |
| namespace Flayed.JsonConverterDemo | |
| { | |
| public class CustomJsonConverter : JsonConverter | |
| { | |
| public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
| { | |
| // Make sure the value type is correct | |
| if (!(value is Dictionary<string, string>)) return; | |
| Dictionary<string, string> field = (Dictionary<string, string>)value; | |
| // Custom fields are an object of key value pairs | |
| writer.WriteStartObject(); | |
| foreach (string key in field.Keys) | |
| { | |
| writer.WritePropertyName(key); | |
| serializer.Serialize(writer, field[key]); | |
| } | |
| writer.WriteEndObject(); | |
| } | |
| public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
| { | |
| Dictionary<string, string> customFields = new Dictionary<string, string>(); | |
| JObject jobj = new JObject(reader.Value); | |
| foreach (var prop in jobj) | |
| { | |
| customFields.Add(prop.Key, prop.Value.Value<string>()); | |
| } | |
| return customFields; | |
| } | |
| public override bool CanConvert(Type objectType) | |
| { | |
| return typeof(Dictionary<string, string>).IsAssignableFrom(objectType); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment