First of all, you need to understand what JSON is, you can click https://www.ibm.com/developerworks/cn/web/wa-lo-json/ to learn more about JSON, I will briefly introduce JSON here: JSON stands for Javascrip{filter}t Object Natation, which is a lightweight data exchange format that is ideal for server interaction with Javascrip{filter}t. Like XML, JSON is a plain text-based data format. Since JSON is inherently prepared for Javascrip{filtering}t, the data format of JSON is very simple, you can transfer a simple String, Number, Boolean, an array, or a complex Object object in JSON. In the .NET environment, we use Json.net to serialize and deserialize JSON data.
Start by clicking Connect http://json.codeplex.com/ to download the JSON. .NET plugins and code. Then make a reference Newtonsoft.Json.dll in your project Add namespace: using Newtonsoft.Json; The following are some important methods and examples of JSON serialization and deserialization: JsonConvert.SerializeObject(object value), which has an overload method JsonConvert.SerializeObject(object value, params JsonConverter[] converters). JsonConvert.DeserializeObject(string value, Type type), deserialized, it has an overload method JsonConvert.DeserializeObject(string value, Type type, params JsonConverter[] converters) These two methods can achieve basic serialization and deserialization requirements, see the following examples: First, let's build a Person class code as follows: public class Person { private string name; public string Name { get { return name; } set { name = value; } } private int age; public int Age { get { return age; } set { age = value; } } } 1) Serialization using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Newtonsoft.Json;
namespace JSONnet
{ public partial class test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Person person = new Person(); person. Name = "GoldenEasy"; person. Age = 25;
string strSerializeJSON = JsonConvert.SerializeObject(person); Response.Write(strSerializeJSON); } }
} Output: {"Name":"GoldenEasy","Age":25} 2) deserialization using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Newtonsoft.Json;
namespace JSONnet
{ public partial class test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Person person = new Person(); person. Name = "GoldenEasy"; person. Age = 25; string strSerializeJSON = JsonConvert.SerializeObject(person); Person user = (Person)JsonConvert.DeserializeObject(strSerializeJSON, typeof(Person)); Response.Write(user. Name);
} }
} The output result is: GoldenEasy |