简体   繁体   中英

Serialize enum to const JsonNet

I am using Asp MVC 3 application.

I have an Enum:

public enum EmployeesOptions
    {
        John = 1,
        Peter = 2,
        Andrew = 3
    }

And a MyViewModel class

   public class MyViewModel
    {
        public MyViewModel()
        {
            Employees = new List<EmployeesOptions>()
            {
                EmployeesOptions.John,
                EmployeesOptions.Peter,
                EmployeesOptions.Andrew
            };
        }

        public IEnumerable<EmployeesOptions> Employees { get; set; }
    }

My Controller:

public ActionResult Index()
        {
            var vm = new MyViewModel();
            return View(vm);
        }

In My Index View:

@model MyViewModel

    <script type="text/javascript">
        var jsonString = '@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model))';

        var data = ko.mapping.fromJSON(jsonString);
        omega.franchiseInfo = ko.mapping.fromJS(data);
     </script>

My serialized data coming from the server looks like this:

    Emplyees:[1,2,3]

I want to be like this:

Emplyees:["John","Peter","Andrew"]

What am I missing ?

Update:

var jsonString = '@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model, Newtonsoft.Json.Formatting.None, new Newtonsoft.Json.Converters.StringEnumConverter()))';

This do the job!

If you want this enum type always to be serialized with its string values, you can decorate it with a JsonConverter attribute and the StringEnumConverter class like this:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

[JsonConverter(typeof(StringEnumConverter))]
public enum EmployeesOptions
{
    John = 1,
    Peter = 2,
    Andrew = 3
}

Then you don't need to specify any converter classes in the serializer options anymore.

I tried decorating a List property that holds Enum values with [JsonConverter(typeof(StringEnumConverter))] but understandably that didn't work since it should decorate the Enum type directly.

// Did not work!
[JsonConverter(typeof(StringEnumConverter))]
public List<Assessment.AssessmentFunction> SelectedFunctions { get; set; }

then I did as you suggested and it worked as expected.

var selectedFunctions = @Html.Raw(JsonConvert.SerializeObject(Model.SelectedFunctions,
                                                              new StringEnumConverter()))

Instead of Enum int values now I get Enum strings in the JavaScript code inside a Razor .cshtml view. Just what I needed in a specific situation.

Before

var selectedFunctions = @Html.Raw(Json.Encode(Model.SelectedFunctions))

// Output
var selectedFunctions = [3, 3, 2, 2, 2, 3, 2, 2]

After

var selectedFunctions = @Html.Raw(JsonConvert.SerializeObject(Model.SelectedFunctions,
                                                              new StringEnumConverter()))

// Output
var selectedFunctions = ["Nurse","Nurse","Doctor","Doctor","Doctor","Nurse","Doctor","Doctor"]

You are returning enums, and by default it will display the enum values. You can modify your model like this.

public class MyViewModel
{
    public MyViewModel()
    {
        Employees = new List<EmployeesOptions>()
        {
            EmployeesOptions.John.ToString(),
            EmployeesOptions.Peter.ToString(),
            EmployeesOptions.Andrew.ToString()
        };
    }

    public IEnumerable<EmployeesOptions> Employees { get; set; }
}

By using the .ToString() extension method we can convert enums to the exact thing they are representing to string format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM