C# Json转换操作
枚举类型
Enum为枚举提供基类,其基础类型可以是除
Char 外的任何整型,如果没有显式声明基础类型,则使用Int32。
注意:枚举类型的基类型是除
Char 外的任何整型,所以枚举类型的值是整型值
1、C#将枚举转为字符串(enume->string)
我们的对象中包含枚举类型,在序列化成Json字符串的时候,显示的是枚举类型对应的数字。因为这是枚举的
本质所在,但是很多时候需要在JSON转化的时候做一些操作,使之显示字符串,因为用户需要字符串。
[JsonConverter(typeof(StringEnumConverter))]
举例如下:
在MODEL project上引用Json.net
DLL
然后加上Attribute [JsonConverter(typeof(StringEnumConverter))]
eg:
public enum RecipientStatus { Sent, Delivered, Signed, Declined } public class RecipientsInfoDepartResult { [JsonConverter(typeof(StringEnumConverter))] //属性将枚举转换为string public RecipientStatus status { set; get; } public PositionBeanResult PredefineSign { set; get; } }
2)、利用Enum的静态方法GetName与GetNames
eg : public static string 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 static T GetType<T>(string strType) { T t = (T)Enum.Parse(typeof(T), strType); return t; }
判断某个枚举变量是否在定义中:
RecipientStatus type = RecipientStatus.Sent; Enum.IsDefined(typeof(RecipientStatus), type );
总结
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。