JSON data is needed today, so JSON serialization and deserialization is used. First of all, how to serialize:
1. Serialization and deserialization
First add the System.Runtime.Serialization reference
Object into 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 ()); } }
JSON data converted to object
public static T jsontoobject<t> (string json) where T:class { datacontractjsonserializer ser = new Datacont Ractjsonserializer (typeof (T)); using (MemoryStream ms = new MemoryStream (Encoding.Default.GetBytes (JSON))) { return (T) ser. ReadObject (MS); } }
The program is relatively simple I won't say much, just at the beginning the entity class is this:
[Serializable] Class User {public int: Age {get; set;} public string Name {get; set;} Public User (string name, int.) {Age = age; name = name; } }
Then call:
static void Main (string[] args) { var user1 = new User ("Zhangsan"); var users = new List<user> {user1, new User ("Lisi")}; var strUser1 = Objecttojson (user1); var setusers = Objecttojson (users); }
Add breakpoints to view JSON data,
Somehow there was a k__backingfield in the mess.
2. The K__backingfield solution of the random entry
From the Internet to find a lot of information and do not understand why this problem arises. If you want to know, you can refer to this. But the solution was found here:
You only need to change the entity class to the following form:
[DataContract] Class User { [DataMember] public int Age {get; set;} [DataMember] public string Name {get; set;} Public User (string name, int.) {Age = age; name = name; } }
There will be no k__backingfield under surveillance. The call to convert JSON data to entities is also straightforward:
static void Main (string[] args) { var user1 = new User ("Zhangsan"); var users = new List<user> {user1, new User ("Lisi")}; var strUser1 = Objecttojson (user1); var strusers = Objecttojson (users); var user11 = jsontoobject<user> (strUser1); var users1 = jsontoobject<list<user>> (strusers); }
Serialization and deserialization of JSON and k_backingfield of random entry