In a custom class, I have a generic dictionary which has an enum type for the value type. Please note that the enum type is out of my control (part of a 3rd party assembly).
When I serialize such objet using Newtonsoft, enums are written as integer.
How to serialize enums as string?
I've tried using StringEnumConverter
on the property but it applies only on the property itself, not when a generic is used. As the enum is declared in an external assembly, I can't apply StringEnumConverter directly on the enum.
Here is a repro sample:
Output :
{"ExtendedData":{"First":0,"Second":1}}
Code:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class Program
{
public static void Main()
{
var data = new Data();
data.ExtendedData.Add("First", Foo.Val1);
data.ExtendedData.Add("Second", Foo.Val2);
Console.WriteLine(JsonConvert.SerializeObject(data));
}
public class Data{
private readonly Dictionary<string, Foo> m_ExtendedData = new Dictionary<string, Foo>();
public Dictionary<string, Foo> ExtendedData {get { return m_ExtendedData ; }}
}
// !Actually from an external assembly
public enum Foo{
Val1,
Val2
}
}