Created
December 20, 2018 09:56
-
-
Save mjul/cf23cc84f5e657dd0e05122325239249 to your computer and use it in GitHub Desktop.
A custom Newtonsoft JSON JsonConverter for writing a class instance as a dictionary (JSON object)
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; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Serialization; | |
namespace Foobar | |
{ | |
public class ItemsConverter : JsonConverter | |
{ | |
private void WriteJson(JsonWriter writer, Items items, JsonSerializer serializer) | |
{ | |
var asDictionarySortedByName = | |
new SortedDictionary<string, string>(items.ToDictionary(v => v.Name, v => v.Value)); | |
serializer.Serialize(writer, asDictionarySortedByName); | |
} | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
if (value is Items items) | |
{ | |
WriteJson(writer, items, serializer); | |
} | |
else | |
{ | |
serializer.Serialize(writer, value); | |
} | |
} | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, | |
JsonSerializer serializer) | |
{ | |
throw new NotImplementedException(); | |
} | |
public override bool CanRead => false; | |
public override bool CanWrite => true; | |
public override bool CanConvert(Type objectType) | |
{ | |
return typeof(Items).IsAssignableFrom(objectType); | |
} | |
} | |
public class Items : IEnumerable<Item> { | |
public IEnumerator<Item> GetEnumerator() | |
{ | |
throw new NotImplementedException(); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return GetEnumerator(); | |
} | |
} | |
public class Item | |
{ | |
public string Name; | |
public string Value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment