C# Json转换操纵
罗列范例
Enum为罗列供应基类,其基本范例能够是除
Char 外的任何整型,假如没有显式声明基本范例,则运用Int32。
注重:罗列范例的基范例是除
Char 外的任何整型,所以罗列范例的值是整型值
1、C#将罗列转为字符串(enume->string)
我们的对象中包括罗列范例,在序列化成Json字符串的时刻,显现的是罗列范例对应的数字。由于这是罗列的
实质地点,然则许多时刻须要在JSON转化的时刻做一些操纵,使之显现字符串,由于用户须要字符串。
要领就是:在罗列范例上增加属性标签
[JsonConverter(typeof(StringEnumConverter))]
举例以下:
1)、在定义罗列范例时在范例上声明一个属性即可
在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 );
总结
以上就是C#中enum与string的互相转换的示例的细致内容,更多请关注ki4网别的相干文章!