C# Json转换操作
枚举类型
Enum为枚举提供基类,其基础类型可以是除Char
外的任何整型,如果没有显式声明基础类型,则使用Int32。
注意:枚举类型的基类型是除Char
外的任何整型,所以枚举类型的值是整型值
1、C#将枚举转为字符串(enume->string)
我们的对象中包含枚举类型,在序列化成Json字符串的时候,显示的是枚举类型对应的数字。因为这是枚举的
本质所在,但是很多时候需要在JSON转化的时候做一些操作,使之显示字符串,因为用户需要字符串。
方法就是:在枚举类型上添加属性标签
[JsonConverter(typeof(StringEnumConverter))]
举例如下:
1)、在定义枚举类型时在类型上声明一个属性即可
在MODEL project上引用Json.netDLL
然后加上Attribute [JsonConverter(typeof(StringEnumConverter))]
eg:
public enumRecipientStatus
{
[JsonConverter(typeof(StringEnumConverter))]
Sent,
[JsonConverter(typeof(StringEnumConverter))]
Delivered,
[JsonConverter(typeof(StringEnumConverter))]
Signed,
[JsonConverter(typeof(StringEnumConverter))]
Declined
}
当然你还要加上命名空间, using Newtonsoft.Json.Linq;之类的东西,快捷键 Alt + F10,自动添加。public classRecipientsInfoDepartResult
{
[JsonConverter(typeof(StringEnumConverter))]//属性将枚举转换为string
public RecipientStatus status {set;
get; }
public PositionBeanResult PredefineSign {set;
get; }
}
2)、利用Enum的静态方法GetName与GetNames
eg : public staticstring
GetName(Type enumType,Object value)
public static string[] GetNames(Type enumType)
例如:Enum.GetName(typeof(Colors),3))与Enum.GetName(typeof(Colors),Colors.Blue))的值都是"Blue"
Enum.GetNames(typeof(Colors))将返回枚举字符串数组
3)、RecipientStatus ty = RecipientStatus.Delivered;
ty.ToString();
2、字符串转枚举(string->enum)
1)、利用Enum的静态方法Parse: Enum.Parse()
原型:public static Object Parse(Type enumType,string value)
eg : (Colors)Enum.Parse(typeof(Colors), "Red");
(T)Enum.Parse(typeof(T),strType)
一个模板函数支持任何枚举类型
protected staticT
GetType<T>(string strType)
{
T t = (T)Enum.Parse(typeof(T),strType);
return t;
}
判断某个枚举变量是否在定义中:
RecipientStatus type =
RecipientStatus.Sent;
Enum.IsDefined(typeof(RecipientStatus),type );