Skip to content

Instantly share code, notes, and snippets.

@davidelettieri
Created February 4, 2020 11:51
Show Gist options
  • Save davidelettieri/9a6d0f7ced6976cbe98f12b3a983f19c to your computer and use it in GitHub Desktop.
Save davidelettieri/9a6d0f7ced6976cbe98f12b3a983f19c to your computer and use it in GitHub Desktop.
Custom serializer ignored when deserializing arrays
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
namespace TestEnumSerialization
{
class Program
{
static void Main(string[] args)
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new EnumDeserializer());
var textValue = JsonConvert.SerializeObject(new[] { new Foo() { Property1 = Test.B } }, settings);
var foos = JsonConvert.DeserializeObject<Foo[]>(textValue);
}
}
public class Foo
{
public Test Property1 { get; set; }
}
public enum Test
{
A,
B
}
public class EnumDeserializer : JsonConverter
{
public override bool CanRead => true;
public override bool CanWrite => true;
public override bool CanConvert(Type objectType) => objectType.IsEnum;
public override object ReadJson(JsonReader reader, System.Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value is null)
return null;
var jo = JObject.Parse(reader.Value.ToString());
var value = jo.Value<string>("id");
return Enum.Parse(objectType, value);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
writer.WriteStartObject();
writer.WritePropertyName("id");
writer.WriteValue(Convert.ToInt32(value));
writer.WritePropertyName("value");
writer.WriteValue(value.ToString());
writer.WriteEndObject();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment