在 C# 中给出以下内容:
[Flags]
public enum MyFlags {
None = 0,
First = 1 << 0,
Second = 1 << 1,
Third = 1 << 2,
Fourth = 1 << 3
}
是否有任何现有的方法ServiceStack.Text
可以序列化为以下 JSON?
{
"MyFlags": {
"None": 0,
"First": 1,
"Second": 2,
"Third": 4,
"Fourth": 8
}
}
目前我正在使用下面的例程,有没有更好的方法来做到这一点?
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();
}