soapergem
soapergem

Reputation: 9989

Are there any attributes for serializing Enums as strings in Json.NET?

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.

Upvotes: 3

Views: 5309

Answers (1)

EZI
EZI

Reputation: 15354

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);

Upvotes: 8

Related Questions