今天需要使用Json数据,所以用到了Json的序列化与反序列化。首先先来说怎么序列化的:
首先添加System.Runtime.Serialization的引用
public static string ObjectToJson(object obj) { DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { ser.WriteObject(ms, obj); return Encoding.Default.GetString(ms.ToArray()); } }
public static T JsonToObject<T>(string json) where T : class { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream(Encoding.Default.GetBytes(json))) { return (T)ser.ReadObject(ms); } }
程序比较简单我就不多说了,刚开始实体类是这样的:
[Serializable] class User { public int Age { get; set; } public string Name { get; set; } public User(string name, int age) { Age = age; Name = name; } }
然后调用:
static void Main(string[] args) { var user1 = new User("zhangsan", 18); var users = new List<User> { user1, new User("lisi", 23 ) }; var strUser1 = ObjectToJson(user1); var setUsers = ObjectToJson(users); }
加入断点,查看json数据,
居然莫名其妙出现了乱入的k__BackingField
从网上找了好多资料也没搞明白是为啥会出现这个问题。想了解的可以参考下这个。不过找到了解决方案,这里记录下:
只需要将实体类改成如下形式:
[DataContract] class User { [DataMember] public int Age { get; set; } [DataMember] public string Name { get; set; } public User(string name, int age) { Age = age; Name = name; } }
再监视下就不会出现k__BackingField。Json数据转换成实体的调用也很简单:
static void Main(string[] args) { var user1 = new User("zhangsan", 18); var users = new List<User> { user1, new User("lisi", 23 ) }; var strUser1 = ObjectToJson(user1); var strUsers = ObjectToJson(users); var user11 = JsonToObject<User>(strUser1); var users1 = JsonToObject<List<User>>(strUsers); }
新闻热点
疑难解答