Created
February 4, 2020 11:51
-
-
Save davidelettieri/9a6d0f7ced6976cbe98f12b3a983f19c to your computer and use it in GitHub Desktop.
Custom serializer ignored when deserializing arrays
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 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