1

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
    }
}
Steve B
  • 36,818
  • 21
  • 101
  • 174
  • @PatrickHofman, I disagree. Linked question in about changing the functionality for dictionaries, keys to be specific. This case only requires adding a `JsonConverter`, which is nearly not as drastic. See https://dotnetfiddle.net/c6JlZl – kiziu Sep 26 '16 at 12:48
  • For your problem you can write custom JsonConverter. Good example you can see here: http://stackoverflow.com/questions/21908262/newtonsoft-json-deserializeobject-emtpy-guid-field – eocron Sep 26 '16 at 12:49
  • 2
    you can use: var json = JsonConvert.SerializeObject(data, new StringEnumConverter()); – Justin CI Sep 26 '16 at 12:51
  • @PatrickHofman: you are right, this is a duplicate (wasn't able to find it). And I guess the accepted answer in the duplicate will solve my issue. Thx – Steve B Sep 26 '16 at 12:51
  • One could argue if it is not a duplicate of http://stackoverflow.com/questions/2441290/json-serialization-of-enum-as-string/2870420#2870420. – kiziu Sep 26 '16 at 12:52

1 Answers1

2

You can try this

var data = new Data();

data.ExtendedData.Add("First", Foo.Val1);
data.ExtendedData.Add("Second", Foo.Val2);

var json = JsonConvert.SerializeObject(data, new StringEnumConverter());
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Justin CI
  • 2,693
  • 1
  • 16
  • 34