今天需要采取Json数据,所以用到了Json的序列化与反序列化。首先先来说怎么序列化的:

1.序列化与反序列化

  首先补充加System.Runtime.Serialization的援

json 1

 

Object转换成Json文件:

      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());
            }
        }

Json数据易成Object 

    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数据,

json 2

甚至莫名其妙冒出了乱入的k__BackingField

2.乱入的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;
        }
    }

又监视下便无见面json出现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);
        }

 

相关文章

网站地图xml地图