A concise tutorial on. NET processing JSON

Source: Internet
Author: User

Json.NET is a popular, high-performance JSON framework in. NET.

Characteristics

  1. A flexible JSON serialization conversion. NET object is a JSON string. and convert the JSON string to a. NET object.
  2. LINQ to JSON for manual read and write JSON
  3. Higher performance and speed than the. NET built-in JSON serializer.
  4. JSON for easy reading and writing
  5. Reading or writing JSON from XML
  6. Supports Silverlight and Windows Phone.

    The JSON serializer is a good choice when you read and write JSON that is closely associated with a. NET class. The JSON serializer will automatically read and write the JSON for the related class.

    If you are interested only in JSON data, you do not have a . NET class or JSON associated with JSON that has nothing to do with your class, you need to read and write data manually from the object. In each of these cases, you can use LINQ to JSON. LINQ to JSON allows you to read, write, and modify JSON data more easily in. Net.

    Download json.net from CodePlex or install using NuGet.

    Pm> Install-package Newtonsoft.json

    Json.NET List

    http://json.codeplex.com/releases/view/74287

    Json.NET 4.0 Release 3 address available

    http://json.codeplex.com/releases/view/74287#DownloadId=287841

    For more information on JSON, see: http://james.newtonking.com/projects/json-net.aspx

    First, construct a simple class employee

    public class employee{public        string Eid{get;set;}        public string Ename{get;set;}        public string Esex{get;set;}        public datetime Birthday{get;set;}}


    JSON serialization vs. deserialization scheme

      1. Using Json.NET to handle JSON serialization and deserialization
Serialization method private String Jsonserialize (employee emp) {return Newtonsoft.Json.JsonConvert.SerializeObject (EMP);} Deserialization Method Private Employee Jsondeserialize (string json) {return (employee) ( Newtonsoft.Json.JsonConvert.DeserializeObject (Json, typeof (Employee)));}

    1. serialization, deserialization using JavaScriptSerializer
          The serialization method is private string jsonserialize (employee EMP) {return new System.Web.Script.Serialization.JavaScriptSerializer (). Serialize (EMP);} Deserializes private string Jsondeserialize (string json) {return (employee) (new System.Web.Script.Serialization.JavaScriptSerializer (). Deserialize (json,typeof (employee)));}

    1. Serializing and deserializing JSON through class DataContractJsonSerializer

      Serialization methods

private string jsonserialize (employee emp) {        System.Runtime.Serialization.Json.DataContractJsonSerializer Dcjs = New System.Runtime.Serialization.Json.DataContractJsonSerializer (typeof (Employee));        System.IO.MemoryStream ms = new System.IO.MemoryStream ();        Dcjs. WriteObject (MS, EMP);        String json = System.Text.Encoding.UTF8.GetString (Ms. ToArray ());        Ms. Close ();        return JSON;         

Deserialization method

Private employee Jsondeserialize (string json) {     System.Runtime.Serialization.Json.DataContractJsonSerializer DCJS = new System.Runtime.Serialization.Json.DataContractJsonSerializer (typeof (Employee));    System.IO.MemoryStream ms = new System.IO.MemoryStream (System.Text.Encoding.UTF8.GetBytes (JSON)); Employee obj = ( Employee) (DCJS. ReadObject (MS)); return obj;        

    1. Get Json data through Newtonsoft.Json.Linq.JObject

    1. 5. LINQ to JSON Example
String json = @ "{" "  Name" ":" "Apple" ","  "expiry" ": New Date (1230422400000)," "" Price "  : 3.99," "  Sizes" ": [" "Small" "," "    Medium" "," "    Large" "  

JSON serialization and deserialization of date-time processing

JsonThe format does not directly support the date and time.DatetimeValue values are displayed as"/date (700000+0500)/"form ofjson string, where the first digit (in the GMT 1970 year month 1 Span style= "font-family: the song Body;" The number of milliseconds elapsed since midnight at normal time (non-daylight savings). The number can be negative to indicate the previous time. Examples include Part optional, which indicates that the time belongs to local utc

date formats are processed using DataContractJsonSerializer serialization, and other ( anti- ) serialization schemes are used in the same way. The design idea is to match the regular expression and replace the date data in the JSON with the normal date format.

Serialization methods

private string jsonserialize (employee emp) { System.Runtime.Serialization.Json.DataContractJsonSerializer DCJS = new System.Runtime.Serialization.Json.DataContractJsonSerializer (typeof (employee)); System.IO.MemoryStream ms = new System.IO.MemoryStream ();d CJs. WriteObject (MS, EMP); string json = System.Text.Encoding.UTF8.GetString (Ms. ToArray ()); Ms. Close ();//Replace JSON time with string p = @ "\\/date\ ((\d+) \) \\/"; System.Text.RegularExpressions.MatchEvaluator me = new System.Text.RegularExpressions.MatchEvaluator ( convertjsondatetodatastring); System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex (p); json = regex.  Replace (JSON, ME); return json;} private String convertjsondatetodatastring (System.Text.RegularExpressions.Match m) {string result = string. Empty;datetime dt = new DateTime (1970,1,1);d t = dt. Addmilliseconds (Long. Parse (M.groups[1]. Value));d t = dt. ToLocalTime (); result = dt. ToString ("Yyyy-mm-dd HH:mm:ss"); return result;} 

Deserialization method

Private employee Jsondeserialize (string json) {string p = @ "\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; System.Text.RegularExpressions.MatchEvaluator me = new System.Text.RegularExpressions.MatchEvaluator ( Convertdatestringtojsondate); System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex (p); json = Reg. Replace (JSON, ME); System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs=new System.Runtime.Serialization.Json.DataContractJsonSerializer (typeof (employee)); System.IO.MemoryStream ms=new System.IO.MemoryStream (System.Text.Encoding.UTF8.GetBytes (JSON)); Employee emp= ( Employee) Dcjs. ReadObject (MS); return EMP;} private String Convertdatestringtojsondate (System.Text.RegularExpressions.Match m) {string result = string. Empty;datetime dt = DateTime.Parse (M.groups[0]. Value);d t = dt. ToUniversalTime (); TimeSpan ts = dt-datetime.parse ("1970-1-1"); result = string. Format ("\\/date ({0}+0800) \\/", TS. TotalMilliseconds); return result;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.