Your problem is that you are applying StringEnumConverter
too late in the process. Json.NET converts the enum
to a string or integer when your POCO is serialized to a JObject
hierarchy, but you are supplying the converter later, when the JObject
is finally formatted as a string.
Instead, supply the converter when serializing to JObject
by using JObject.FromObject(Object, JsonSerializer)
and constructing a serializer with the desired settings:
var response = JObject.FromObject(
new
{
Error = new
{
Message = "Test",
Code = ErrorCode.A
}
},
JsonSerializer.CreateDefault(new JsonSerializerSettings { Converters = { new StringEnumConverter() } })
)
.ToString(Formatting.None);
Sample fiddle here.
(You might reasonably ask, when do the converters supplied to JToken.ToString(Formatting,JsonConverter[])
ever matter? While, in general, converters are applied during serialization to JToken
, these converters are useful to control formatting of value types that Newtonsoft stores directly inside JValue.Value
without modification. Most notably, DateTime
values are stored directly in the JToken
hierarchy without conversion during serialization. This, in turn, happens because Newtonsoft recognizes DateTime
values during tokenizing of a JSON stream by JsonTextReader
, necessitating the ability to store the resulting DateTime
objects inside a JValue
. For details see here and here. Conversely, as Json.NET does not try to recognize enum values during parsing, there was never a need to retain them in a JToken
hierarchy. Thus they're converted to strings or integers during the serialization phase.)