Let’s recap serialization from the previous section, which converts an entity object into a JSON string.
Serialization
WebInfo webInfo = new WebInfo();
webInfo.age = 4;
webInfo.webname = "FoxDevelop";
webInfo.website = "foxdevelop.com";
webInfo.students = new Person[] { new Person { name = "Tom" }, new Person { name = "Jim" } };
// Convert the webinfo object to a JSON string
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(sw);
new JsonSerializer().Serialize(writer, webInfo);
string json = sw.GetStringBuilder().ToString();Code language: JavaScript (javascript)
Generated JSON output
{"webname":"FoxDevelop","website":"foxdevelop.com","age":4,"students":[{"name":"Zhang San"},{"name":"Li Si"}]}Code language: JSON / JSON with Comments (json)
Deserialization
Convert a JSON string back to an entity object
Method 1 (low‑level Reader approach)
WebInfo model = new JsonSerializer()
.Deserialize(new JsonTextReader(new StringReader(json)), typeof(WebInfo)) as WebInfo;Code language: JavaScript (javascript)
Method 2 (concise generic syntax, Newtonsoft.Json)
WebInfo model = JavaScriptConvert.DeserializeObject<WebInfo>(json);Code language: HTML, XML (xml)
new JsonSerializer().Deserialize(new JsonTextReader(new StringReader(jsonString)), typeof(ClassName) as ClassName
With the above methods, we can deserialize JSON into entity objects.
Alternative usage
JavaScriptConvert.DeserializeObject<NodeInfo>(jsonText)
Serialization and deserialization
Previous: Introduction