3

Here's what I have so far:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace MyProject
{
    [TestClass]
    public class MyClass
    {
        [TestMethod]
        public void VerifyJsonString()
        {
            var json = new JObject
            {
                new JProperty("Thing", Things.Cats)
            };
            var actual = json.ToString(Formatting.None);
            const string expected = "{\"Thing\":\"Cats\"}";
            Assert.AreEqual(expected, actual);
        }
    }

    [JsonConverter(typeof(StringEnumConverter))]
    public enum Things
    {
        Apples,
        Bananas,
        Cats
    }
}

Unfortunately, this test fails as it serializes it as {"Thing":2} instead. How can I get it to serialize the enum properly? I realize I could explicitly call .ToString() on it but I don't want to. I'd rather have some attribute so I don't have to remember to do that each time.

soapergem
  • 9,263
  • 18
  • 96
  • 152

1 Answers1

8

Just use StringEnumConverter

var actual = json.ToString(Formatting.None, 
                           new Newtonsoft.Json.Converters.StringEnumConverter());

EDIT

Is there no way to tell it to automatically use that converter every time you call ToString()?

JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { 
                Converters = new List<Newtonsoft.Json.JsonConverter>() { new Newtonsoft.Json.Converters.StringEnumConverter() } 
};

var actual = JsonConvert.SerializeObject(json);
EZI
  • 15,209
  • 2
  • 27
  • 33
  • Does it have to be in the method call though? Is there no way to tell it to automatically use that converter every time you call ToString()? – soapergem Jul 09 '15 at 21:49
  • +1 Was just typing out an answer just like this. Add the serialiser to the default settings. – christophano Jul 09 '15 at 21:58