Last active
August 29, 2015 14:06
-
-
Save tugberkugurlu/c294fbc55fe28c2c3b26 to your computer and use it in GitHub Desktop.
JSON.NET (Newtonsoft.Json) Custom converter
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.Collections.Generic; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Converters; | |
using System.Runtime.Serialization; | |
namespace ConsoleApplication11 | |
{ | |
[DataContract] | |
public enum JsonPatchOperationType | |
{ | |
[EnumMember(Value = "add")] | |
Add = 0, | |
[EnumMember(Value = "remove")] | |
Remove = 1, | |
[EnumMember(Value = "replace")] | |
Replace = 2 | |
} | |
public class JsonPatchOperation | |
{ | |
[JsonConverter(typeof(StringEnumConverter))] | |
public JsonPatchOperationType Operation { get; set; } | |
public string PropertyName { get; set; } | |
public object Value { get; set; } | |
} | |
[JsonConverter(typeof(JsonPatchDocumentConverter))] | |
public class JsonPatchDocument | |
{ | |
private readonly IEnumerable<JsonPatchOperation> _docs; | |
public JsonPatchDocument(IEnumerable<JsonPatchOperation> docs) | |
{ | |
_docs = docs; | |
} | |
public IEnumerable<JsonPatchOperation> Operations { get { return _docs; } } | |
} | |
// http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization/ | |
public class JsonPatchDocumentConverter : JsonConverter | |
{ | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
JsonPatchDocument jDoc = (JsonPatchDocument)value; | |
serializer.Serialize(writer, jDoc.Operations); | |
} | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
throw new NotImplementedException(); | |
} | |
public override bool CanConvert(Type objectType) | |
{ | |
return typeof(JsonPatchDocument).IsAssignableFrom(objectType); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
JsonPatchDocument jDoc = new JsonPatchDocument(new[] | |
{ | |
new JsonPatchOperation | |
{ | |
Operation = JsonPatchOperationType.Add, | |
PropertyName = "/a/b/c", | |
Value = "foo" | |
}, | |
new JsonPatchOperation | |
{ | |
Operation = JsonPatchOperationType.Remove, | |
PropertyName = "/a/foo", | |
Value = "bar" | |
} | |
}); | |
string result = JsonConvert.SerializeObject(jDoc); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment