Skip to content

Instantly share code, notes, and snippets.

@amitlzkpa
Created August 3, 2018 18:44
Show Gist options
  • Save amitlzkpa/d0ed51da3f5ae4bd189d0c7c43e4740e to your computer and use it in GitHub Desktop.
Save amitlzkpa/d0ed51da3f5ae4bd189d0c7c43e4740e to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
class MyClass {
public int myInt = 42;
public List<int> myList = new List<int>();
}
class MyClassSerializer : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(MyClass).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jsonObject = JObject.Load(reader);
MyClass mc = new MyClass();
JToken myInt = jsonObject.GetValue("MyInt");
mc.myInt = myInt.Value<int>();
JToken myList = jsonObject.GetValue("MyList");
foreach (JToken listItem in myList.Children())
{
mc.myList.Add(listItem.Value<int>());
}
return mc;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.Formatting = Formatting.Indented;
MyClass mc = value as MyClass;
writer.WriteStartObject();
writer.WritePropertyName("MyInt");
writer.WriteValue(mc.myInt);
writer.WritePropertyName("MyList");
writer.WriteStartArray();
foreach (int i in mc.myList)
{
writer.WriteValue(i);
}
writer.WriteEndArray();
writer.WriteEndObject();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment