JSON serialization deserialization

Source: Internet
Author: User
Tags string to json
JSON is a data format specially designed for JavaScript code running on web pages in a browser. More and more scenarios are using JSON in website applications. This article introduces the serialization and deserialization of JSON in ASPNET. It mainly introduces the serialization and deserialization of JSON and how ASPNET serializes and deserializes JSON.

 

 

 

JSON is a data format specially designed for JavaScript code running on web pages in a browser. More and more scenarios are using JSON in website applications. This article introduces ASP. net json serialization and deserialization, mainly a brief introduction to JSON, ASP.. NET how to serialize and deserialize the processing of date, set, and dictionary in serialization and deserialization.

1. Introduction to JSON

JSON (JavaScript Object Notation, JavaScript Object Notation) is a lightweight data exchange format.

JSON is a set of "name-value pairs. The structure consists of braces '{}', braces '[]', comma ',', colons ':', and double quotation marks '. The data types include Object, Number, boolean, String, Array, and NULL.

JSON has the following forms:

An Object is an unordered set of "name-value pairs". An Object starts with "{" and ends. Each "name" is followed by one ":". Multiple "name-value pairs" are separated by commas. For example:

Var user = {name: James, gender: male, birthday}

An Array is an ordered set of values. An Array starts with "[" and ends with "]" and is separated. For example:

Var userlist = [{user: {name: Zhang San, gender: male, birthday: 1980-8-8 }}, {user: {name: Li Si, gender: male, birthday: 1985-5-8}];

A String is a collection of any number of Unicode characters enclosed by double quotes. It is escaped using a backslash.

 

Ii. serialize and deserialize JSON data

You can use the DataContractJsonSerializer class to serialize a type instance to a JSON string and deserialize the JSON string to a type instance. DataContractJsonSerializer in System. runtime. serialization. in the Json namespace ,. NET Framework 3.5 is included in System. serviceModel. web. dll, you need to add a reference to it ;. NET Framework 4 in the System. runtime. serialization.

Code for serialization and deserialization using DataContractJsonSerializer:

 

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Web;
   5: using System.Runtime.Serialization.Json;
   6: using System.IO;
   7: using System.Text;
   8:  
   9: /// 
10: // JSON serialization and deserialization helper class
  11: /// 
  12: public class JsonHelper
  13: {
  14:     /// 
15: // JSON serialization
  16:     /// 
  17:     public static string JsonSerializer
 
  (T t)
 
  18:     {
  19:         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
  20:         MemoryStream ms = new MemoryStream();
  21:         ser.WriteObject(ms, t);
  22:         string jsonString = Encoding.UTF8.GetString(ms.ToArray());
  23:         ms.Close();
  24:         return jsonString;
  25:     }
  26:  
  27:     /// 
28: // JSON deserialization
  29:     /// 
  30:     public static T JsonDeserialize
 
  (string jsonString)
 
  31:     {
  32:         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
  33:         MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
  34:         T obj = (T)ser.ReadObject(ms);
  35:         return obj;
  36:     }
  37: }

 

Serialization Demo:

Simple Object Person:

 

   1: public class Person
   2: {
   3:     public string Name { get; set; }
   4:     public int Age { get; set; }
   5: }

 

Serialized as a JSON string:

 

   1: protected void Page_Load(object sender, EventArgs e)
   2: {
   3:     Person p = new Person();
4: p. Name = James;
   5:     p.Age = 28;
   6:  
   7:     string jsonString = JsonHelper.JsonSerializer
 
  (p);
 
   8:     Response.Write(jsonString);
   9: }

 

Output result:

{Age: 28, Name: James}

Deserialization Demo:

 

   1: protected void Page_Load(object sender, EventArgs e)
   2: {
3: string jsonString = {Age: 28, Name: James };
   4:     Person p = JsonHelper.JsonDeserialize
 
  (jsonString);
 
   5: }

 

Running result:

ASP. you can also use JavaScriptSerializer for JSON serialization and deserialization in. NET. web. script. in the Serializatioin namespace, System must be referenced. web. extensions. dll. you can also use JSON. NET.

 

Iii. Processing of JSON serialization and deserialization Date and Time

JSON format does not support date and time. DateTime value is displayed as a JSON string in the format of "/Date (700000 + 0500)/", where the first number (700000 in the provided example) it is the number of milliseconds that have elapsed since midnight, January 1, January 1, 1970 by normal time (non-timeout. This number can be a negative number to indicate the previous time. The example contains "+ 0500", which indicates that the time belongs to the Local type, that is, it should be converted to the Local time zone during deserialization. If this part does not exist, the time is deserialized to Utc.

Modify the Person class and add LastLoginTime:

 

   1: public class Person
   2: {
   3:     public string Name { get; set; }
   4:     public int Age { get; set; }
   5:     public DateTime LastLoginTime { get; set; }
   6: }

 

   1: Person p = new Person();
2: p. Name = James;
   3: p.Age = 28;
   4: p.LastLoginTime = DateTime.Now;
   5:  
   6: string jsonString = JsonHelper.JsonSerializer
 
  (p);
 

 

Serialization result:

{Age: 28, LastLoginTime:/Date (1294499956278 + 0800)/, Name: James}

1. Use a regular expression to replace the regular expression in the background. Modify JsonHelper:

 

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Web;
   5: using System.Runtime.Serialization.Json;
   6: using System.IO;
   7: using System.Text;
   8: using System.Text.RegularExpressions;
   9:  
  10: /// 
11: // JSON serialization and deserialization helper class
  12: /// 
  13: public class JsonHelper
  14: {
  15:     /// 
16: // JSON serialization
  17:     /// 
  18:     public static string JsonSerializer
 
  (T t)
 
  19:     {
  20:         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
  21:         MemoryStream ms = new MemoryStream();
  22:         ser.WriteObject(ms, t);
  23:         string jsonString = Encoding.UTF8.GetString(ms.ToArray());
  24:         ms.Close();
25: // Replace the Json Date string
  26:         string p = @\/Date((d+)+d+)\/;
  27:         MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
  28:          Regex reg = new Regex(p);
  29:         jsonString = reg.Replace(jsonString, matchEvaluator);
  30:         return jsonString;
  31:     }
  32:  
  33:     /// 
34: // JSON deserialization
  35:     /// 
  36:     public static T JsonDeserialize
 
  (string jsonString)
 
  37:     {
38: // convert the string in the yyyy-MM-dd HH: mm: ss format to the/Date (1294499956278 + 0800)/format
  39:         string p = @d{4}-d{2}-d{2}sd{2}:d{2}:d{2};
  40:         MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
  41:         Regex reg = new Regex(p);
  42:         jsonString = reg.Replace(jsonString, matchEvaluator);
  43:         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
  44:         MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
  45:         T obj = (T)ser.ReadObject(ms);
  46:         return obj;
  47:     }
  48:  
  49:     /// 
50: // convert the Json serialization time from/Date (1294499956278 + 0800) to a string
  51:     /// 
  52:     private static string ConvertJsonDateToDateString(Match m)
  53:     {
  54:         string result = string.Empty;
  55:         DateTime dt = new DateTime(1970,1,1);
  56:         dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
  57:         dt = dt.ToLocalTime();
  58:         result = dt.ToString(yyyy-MM-dd HH:mm:ss);
  59:         return result;
  60:     }
  61:  
  62:     /// 
63: // convert the time string to Json time
  64:     /// 
  65:     private static string ConvertDateStringToJsonDate(Match m)
  66:     {
  67:         string result = string.Empty;
  68:         DateTime dt = DateTime.Parse(m.Groups[0].Value);
  69:         dt = dt.ToUniversalTime();
  70:         TimeSpan ts = dt - DateTime.Parse(1970-01-01);
  71:         result = string.Format(\/Date({0}+0800)\/,ts.TotalMilliseconds);
  72:         return result;
  73:     }
  74: }

 

Serialization Demo:

 

   1: Person p = new Person();
2: p. Name = James;
   3: p.Age = 28;
   4: p.LastLoginTime = DateTime.Now;
   5:  
   6: string jsonString = JsonHelper.JsonSerializer
 
  (p);
 

 

Running result:

{Age: 28, LastLoginTime: 01:00:56, Name: James}

Deserialization Demo:

String json = {Age: 28, LastLoginTime :? 1-01-09 00:30:00, Name: James };
p=JsonHelper.JsonDeserialize
 
  (json);
 

Running result:

The application scope of string replacement in the background is relatively narrow, and it is more difficult to consider the globalization of multiple languages.

2. Processing with JavaScript

 

   1: function ChangeDateFormat(jsondate) {
   2:     jsondate = jsondate.replace(/Date(, ).replace()/, );
   3:     if (jsondate.indexOf(+) > 0) {
   4:         jsondate = jsondate.substring(0, jsondate.indexOf(+));
   5:     }
   6:     else if (jsondate.indexOf(-) > 0) {
   7:         jsondate = jsondate.substring(0, jsondate.indexOf(-));
   8:     }
   9:  
  10:     var date = new Date(parseInt(jsondate, 10));
  11:     var month = date.getMonth() + 1 < 10 ? 0 + (date.getMonth() + 1) : date.getMonth() + 1;
  12:     var currentDate = date.getDate() < 10 ? 0 + date.getDate() : date.getDate();
  13:     return date.getFullYear() + - + month + - + currentDate;
  14: }

 

Simple Demo:

ChangeDateFormat(/Date(1294499956278+0800)/);

Result:

2011-1-8
4. JSON serialization and deserialization collection, dictionary, and Array Processing

In JSON data, all sets, dictionaries, and arrays are represented as arrays.

List Serialization:

 

   1: List
 
   list = new List
  
   ()
  
 
   2: {
3: new Person () {Name = James, Age = 28 },
4: new Person () {Name = Li Si, Age = 25}
   5: };
   6:  
   7: string jsonString = JsonHelper.JsonSerializer
 
  >(list);
 

 

Serialization result:

[{Age: 28, Name: Zhang San}, {Age: 25, Name: Li Si}]

The Dictionary cannot be directly used for JSON. The conversion of a Dictionary into JSON is not in the same format as the original Dictionary. Instead, the Dictionary uses the Key of the Dictionary as the value of the name "Key, use the Value of Dictionary as the Value named "Value. For example:

 

   1: Dictionary
 
   dic = new Dictionary
  
   ();
  
 
2: dic. Add (Name, James );
   3: dic.Add(Age, 28);
   4:  
   5: string jsonString = JsonHelper.JsonSerializer < Dictionary
 
  >(dic);
 

 

Serialization result:

 

1: [{Key: Name, Value: Zhang San}, {Key: Age, Value: 8}]

 

Related Article

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.