Reputation: 111
I have in my enum this:
namespace MyServer.Aluno.Model
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
public enum AlunoSexo
{
[Display(Name = "Masculino")]
M = 1,
[Display(Name = "Feminino")]
F = 2,
}
}
How to make HttpGet to display it on Json in my api?
Upvotes: 1
Views: 103
Reputation: 6905
You can use this function:
public class EnumModel<T>
{
public string StringValue { get; set; }
public T EnumValue { get; set; }
public int IntValue { get; set; }
public string DisplayName { get; set; }
public static List<EnumModel<T>> GetModel()
{
var t = typeof(T);
var fields = t.GetFields();
return fields.Where(x => x.CustomAttributes.Any(z => z.NamedArguments.Any(n => n.MemberName == "Name"))).Select(x =>
new EnumModel<T>
{
StringValue = x.Name,
EnumValue = (T)Enum.Parse(t, x.Name),
IntValue = (int)Enum.Parse(t, x.Name),
DisplayName = (string)x.CustomAttributes.Select(z => z.NamedArguments.First(n => n.MemberName == "Name").TypedValue).First().Value,
}).ToList();
}
}
Usage:
var modelList = EnumModel<AlunoSexo>.GetModel();
string json = new JavaScriptSerializer().Serialize(modelList);
return new View(ModelList);
Your JSON will look like this:
[
{
"StringValue":"M",
"EnumValue":1,
"IntValue":1,
"DisplayName":"Masculino"
},
{
"StringValue":"F",
"EnumValue":2,
"IntValue":2,
"DisplayName":"Feminino"
}
]
Alternatively you can use a custom library for your Javascript Serialization like Newtonsoft.Json
and change the way you decorate your enum
to work that library.
A couple examples of that here: How to tell JSON.NET StringEnumConverter to take DisplayName?
Upvotes: 2