Skip to content

Instantly share code, notes, and snippets.

@mjul
Created December 20, 2018 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjul/cf23cc84f5e657dd0e05122325239249 to your computer and use it in GitHub Desktop.
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)
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