Json serialization and deserialization, as well as chaotic k_BackingField and jsonk_backingfield
Json data needs to be used today, so Json serialization and deserialization are used. First, let's talk about how to serialize:
1. serialization and deserialization
First, add the reference of System. Runtime. Serialization.
Convert an Object to a Json file:
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()); } }
Convert Json data to 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); } }
The program is relatively simple and I will not talk about it much. At the beginning, the object class was like this:
[Serializable] class User { public int Age { get; set; } public string Name { get; set; } public User(string name, int age) { Age = age; Name = name; } }
Then call:
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); }
Add a breakpoint to view json data,
Why is there a messy k _ BackingField?
2. Solution for the random k _ BackingField
I found a lot of information on the Internet and didn't figure out why this problem occurs. For more information, see. However, the solution is found, which is recorded here:
You only need to change the object class to the following format:
[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; } }
Then, there will be no k _ BackingField. The call to convert Json data into objects is also simple:
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); }