1

We want to serialize an object to JSON with Newton.JSON, but this Object use an enum and is then converted in the underlying int (see 'Datatype' in JSON below). How can ve proceed to get the "enum string" representation?

{
    "Timestamp": 1538568112852,
    "Metrics": [{
        "Name": "bdSeq",
        "Timestamp": 1538568112852,
        "Datatype": 4,
        "IsNull": false,
        "LongValue": 0
    }],
    "Seq": 18446744073709551615
}
Edword
  • 80
  • 11
jean.noel
  • 61
  • 4
  • See [this answer](https://stackoverflow.com/a/2870420) to [.NET - JSON serialization of enum as string](https://stackoverflow.com/q/2441290), [Serialize enum as a string in JSON.NET using attributes](https://stackoverflow.com/q/10387243) and also [How to tell Json.Net globally to apply the StringEnumConverter to all enums](https://stackoverflow.com/q/7427909). – dbc Oct 10 '18 at 14:28

1 Answers1

0

You can substitute standard JsonSerializer with your own.

In startup.cs:

services.AddScoped(typeof(JsonSerializer), typeof(EnumAsStringSerializer));

And the class itself:

 public class EnumAsStringSerializer : JsonSerializer
    {
        public EnumAsStringSerializer()
        {
            this.ContractResolver = new CamelCasePropertyNamesContractResolver();
            this.Converters.Add(new StringEnumConverter
            {
                CamelCaseText = true,
            });
        }
    }
Maxim Zabolotskikh
  • 3,091
  • 20
  • 21