将C#枚举定义序列化为Json [英] Serialize C# Enum Definition to Json
本文介绍了将C#枚举定义序列化为Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中给出以下内容:
Given the following in C#:
[Flags]
public enum MyFlags {
None = 0,
First = 1 << 0,
Second = 1 << 1,
Third = 1 << 2,
Fourth = 1 << 3
}
ServiceStack.Text中是否有任何现有方法
序列化为以下JSON?
Are there any existing methods in ServiceStack.Text
for serializing to the following JSON?
{
"MyFlags": {
"None": 0,
"First": 1,
"Second": 2,
"Third": 4,
"Fourth": 8
}
}
当前我正在使用以下例程,是否有更好的方法
Currently I'm using the routine below, are there better ways to do this?
public static string ToJson(this Type type)
{
var stringBuilder = new StringBuilder();
Array values = Enum.GetValues(type);
stringBuilder.Append(string.Format(@"{{ ""{0}"": {{", type.Name));
foreach (Enum value in values)
{
stringBuilder.Append(
string.Format(
@"""{0}"": {1},",
Enum.GetName(typeof(Highlights), value),
Convert.ChangeType(value, value.GetTypeCode())));
}
stringBuilder.Remove(stringBuilder.Length - 1, 1);
stringBuilder.Append("}}");
return stringBuilder.ToString();
}
推荐答案
最好不要填充 Dictionary< string,int>
或类型化的DTO并将其序列化。
You're better off populating a Dictionary<string,int>
or a Typed DTO and serializing that.
这篇关于将C#枚举定义序列化为Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文