简体   繁体   English

将枚举值和名称序列化为JSON

[英]Serialize Enum Values and Names to JSON

This question is related, but IMHO not identical to 这个问题是相关的,但恕我直言不等同于

Whilst testing, I've also stumbled across this culprit LinqPad which made my life difficult: Why does LINQPad dump enum integer values as strings? 在进行测试的同时,我也偶然发现了这个使我生活艰难的元凶LinqPad: 为什么LINQPad会将枚举整数值作为字符串转储?

Now, my actual question: My application (in particular SyncFusion component datasources, such as MultiSelect) requires enumerations in JSON format, eg something like this: 现在,我的实际问题是:我的应用程序(特别是SyncFusion组件数据源,例如MultiSelect)需要JSON格式的枚举,例如:

[ {"Id":0,"Name":"Unknown"},{"Id":1,"Name":"Open"},{"Id":2,"Name":"Closed"},{"Id":3,"Name":"Approve"} ]

UPDATE As dbc pointed out, my question may not have been clear enough. 更新正如dbc指出的那样,我的问题可能还不够清楚。 I do not want to serialize one entry of the enumeration, but the whole struct. 我不想序列化枚举的一个条目,而是整个结构。 The JSON could then be used for a data source in Javascript, eg for a , simplified: <option value=0>Unknown</option> <option value=1>Open</option> etc 然后可以将JSON用于Javascript中的数据源,例如,用于,简化: <option value=0>Unknown</option> <option value=1>Open</option> etc

The JSON object is identical to an Enum in a namespace (with the exception that I have given the a property name to the Key and Value of each entry: JSON对象与名称空间中的Enum相同(但我为每个条目的Key和Value赋予了一个属性名称:

public enum ListOptions
{
    Unknown = 0,
    Open = 1,
    Closed = 2,
    Approve = 3
}

I've struggled with Enums, all the other approaches such as specifying a Json StringConverter etc did't yield all options in an array, so I ended up using Linq. 我在Enums方面苦苦挣扎,其他所有方法(例如指定Json StringConverter等) 无法产生数组中的所有选项,因此我最终使用了Linq。 My View Model now has a string property like this: 我的视图模型现在具有如下字符串属性:

public string CrewListOption => JsonConvert.SerializeObject(Enum.GetValues(typeof(ListOptions))
        .Cast<int>()
        .Select(e => new { Id = (int)  e, Name = typeof(ListOptions).GetEnumName(e) }));

Given that I'm pretty much a beginner with ASP.Net Core, I find it hard to believe that this should be a good solution. 鉴于我几乎是ASP.Net Core的初学者,所以我很难相信这应该是一个好的解决方案。 Yet I find it hard to find straight-forward better examples of the same thing. 然而,我发现很难找到同一件事的直接更好的例子。

I'd appreciate it if you might be able to help me improve this, and make it potentially more generically useful to "export" whole enumerations to JSON. 如果您能够帮助我改善此问题,并使其对于将整个枚举“导出”到JSON而言可能更通用,那么我将不胜感激。

Here's the full LinqPad (where Newtonsoft.Json is imported from GAC): 这是完整的LinqPad(Newtonsoft.Json从GAC导入的地方):

void Main()
{   
    Enum.GetValues(typeof(ListOptions)).Cast<int>().Select(e => new { Id = e, Name = (ListOptions) e } ).Dump(); // these are identical, except for the typeof()
    Enum.GetValues(typeof(ListOptions)).Cast<int>().Select(e => new { Id = (int)  e, Name = typeof(ListOptions).GetEnumName(e) }).Dump(); // is typeof(MyEnumType) better?
    string JsonString = JsonConvert.SerializeObject(Enum.GetValues(typeof(ListOptions)).Cast<int>().Select(e => new { Id = (int)  e, Name = typeof(ListOptions).GetEnumName(e) }));
    JsonString.Dump(); // [{"Id":0,"Name":"Unknown"},{"Id":1,"Name":"Open"},{"Id":2,"Name":"Closed"},{"Id":3,"Name":"Approve"}]
}

public enum ListOptions { 
    Unknown = 0,
    Open = 1,
    Closed = 2,
    Approve = 3 
};

You may have static method like 您可能有类似的静态方法

public static EnumToDictionary<string, string> EnumToDictionary<T>() where T: Enum
{
    var res = Enum.GetValues(typeof(T)).Cast<T>()
        .ToDictionary(e => Convert.ToInt32(e).ToString(), e => e.ToString());

    return res;
}

then for Serializing as object 然后用于序列化为对象

var enumValues=  EnumToDictionary<ListOptions>();
var result = JsonConvert.SerializeObject(enumValues);

for serializing as array 用于序列化为数组

var enumValues=  EnumToDictionary<ListOptions>().ToArray();
var result = JsonConvert.SerializeObject(enumValues);

Here is an example from Microsoft Docs that convert Enum to Dictionary 这是来自Microsoft Docs的示例,该示例将Enum转换为Dictionary

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters#enum-constraints https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters#enum-constraints

Then you can serialize the dictionary to JSON. 然后,您可以将字典序列化为JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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