Serialize/return enum as string from asp.net core api action

Jai
Jai
2 Points
1 Posts

I want to serialize enum as string instead of index integer value from the rest api action. I'm trying with following model using Newtonsoft serializer:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Text;

namespace ViewModel
{
    public class MyResponse
    {
        [JsonConverter(typeof(StringEnumConverter))]
        public Status Status { get; set; }
        public string StatusMessage { get; set; }
    }
}
public enum Status
{        
    CANCELLED = 0,
    COMPLETED = 1
}

But, I'm not getting expected result. It's still serializing as integer value.

What is missing here?

Views: 11927
Total Answered: 2
Total Marked As Answer: 1
Posted On: 20-Aug-2020 02:20

Share:   fb twitter linkedin
Answers
Smith
Smith
2890 Points
78 Posts
         

ASP.NET Core 3.1 uses built-in JSON serialization.
Use System.Text.Json.Serialization.JsonStringEnumConverter as:

using System.Text.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Text;

namespace ViewModel
{
    public class MyResponse
    {
        [JsonConverter(typeof(JsonStringEnumConverter))]
        public Status Status { get; set; }
        public string StatusMessage { get; set; }
    }
}
Posted On: 26-Aug-2020 00:43
Rahul Maurya
Rahul M...
4918 Points
28 Posts
         

We can make changes in startup.cs and will apply for all action in the application:

services.AddControllers().AddJsonOptions(o =>
      {
        o.JsonSerializerOptions.IgnoreNullValues = true;
        o.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
      });
Posted On: 18-Sep-2020 00:10
 Log In to Chat