Home Web Front-end JS Tutorial JSON serialization and deserialization implementation methods (with code)

JSON serialization and deserialization implementation methods (with code)

Apr 25, 2018 pm 05:27 PM
javascript json Serialization

这次给大家带来JSON序列化与反序列化实现方法(附代码),JSON序列化与反序列化实现的注意事项有哪些,下面就是实战案例,一起来看一下。

一、JSON简介

 JSON(JavaScript Object Notation,JavaScript对象表示法)是一种轻量级的数据交换格式。

JSON是“名值对”的集合。结构由大括号'{}',中括号'[]',逗号',',冒号':',双引号'“”'组成,包含的数据类型有Object,Number,Boolean,String,Array, NULL等。

JSON具有以下的形式:

对象(Object)是一个无序的“名值对”集合,一个对象以”{”开始,”}”结束。每个“名”后跟着一个”:”,多个“名值对”由逗号分隔。如:

var user={"name":"张三","gender":"男","birthday":"1980-8-8"}
Copy after login

数组(Array)是值的有序集合,一个数组以“[”开始,以“]”结束,值之间使用“,”分隔。如:

复制代码 代码如下:


var userlist=[{"user":{"name":"张三","gender":"男","birthday":"1980-8-8"}},{"user":{"name":"李四","gender":"男","birthday":"1985-5-8"}}];

 字符串(String)是由双引号包围的任意数量的Unicode字符的集合,使用反斜线转义。

二、对JSON数据进行序列化和反序列化

可以使用DataContractJsonSerializer类将类型实例序列化为JSON字符串,并将JSON字符串反序列化为类型实例。DataContractJsonSerializer在SystemRuntimeSerializationJson命名空间下,NET Framework 5包含在SystemServiceModelWebdll中,需要添加对其的引用;NET Framework 4在SystemRuntimeSerialization中。

利用DataContractJsonSerializer序列化和反序列化的代码:

using System;
using SystemCollectionsGeneric;
using SystemLinq;
using SystemWeb;
using SystemRuntimeSerializationJson;
using SystemIO;
using SystemText;
 /// <summary>
 /// JSON序列化和反序列化辅助类
/// </summary>
 public class JsonHelper
{
  /// <summary>
  /// JSON序列化
  /// </summary>
  public static string JsonSerializer<T>(T t)
  {
   DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
   MemoryStream ms = new MemoryStream();
   serWriteObject(ms, t);
   string jsonString = EncodingUTFGetString(msToArray());
   msClose();
   return jsonString;
  } 
  /// <summary>
  /// JSON反序列化
  /// </summary>
  public static T JsonDeserialize<T>(string jsonString)
  {
   DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
   MemoryStream ms = new MemoryStream(EncodingUTFGetBytes(jsonString));
   T obj = (T)serReadObject(ms);
   return obj;
  }
 }
Copy after login

序列化Demo:

简单对象Person:

  public class Person
 {
  public string Name { get; set; }
  public int Age { get; set; }
 }
Copy after login

序列化为JSON字符串:

 protected void Page_Load(object sender, EventArgs e)
{
 Person p = new Person();
 pName = "张三";
  pAge = 28; 
 string jsonString = JsonHelperJsonSerializer<Person>(p);
  ResponseWrite(jsonString);
 }
Copy after login

输出结果:

{"Age":28,"Name":"张三"}
Copy after login

反序列化Demo:

  protected void Page_Load(object sender, EventArgs e)
{
  string jsonString = "{\"Age\":28,\"Name\":\"张三\"}";
  Person p = JsonHelper.JsonDeserialize<Person>(jsonString);
}
Copy after login

运行结果:

ASP.NET中的JSON序列化和反序列化还可以使用JavaScriptSerializer,在System.Web.Script.Serializatioin命名空间下,需引用System.Web.Extensions.dll.也可以使用JSON.NET.

三、JSON序列化和反序列化日期时间的处理

JSON格式不直接支持日期和时间。DateTime值值显示为“/Date(700000+0500)/”形式的JSON字符串,其中第一个数字(在提供的示例中为 700000)是 GMT 时区中自 1970 年 1 月 1 日午夜以来按正常时间(非夏令时)经过的毫秒数。该数字可以是负数,以表示之前的时间。示例中包括“+0500”的部分可选,它指示该时间属于Local类型,即它在反序列化时应转换为本地时区。如果没有该部分,则会将时间反序列化为Utc。

修改Person类,添加LastLoginTime:

  public class Person
 {
 public string Name { get; set; }
  public int Age { get; set; }
  public DateTime LastLoginTime { get; set; }
 }
Copy after login
 Person p = new Person();
 p.Name = "张三";
 p.Age = 28;
 p.LastLoginTime = DateTime.Now; 
 string jsonString = JsonHelper.JsonSerializer<Person>(p);
Copy after login

序列化结果:

{"Age":28,"LastLoginTime":"\/Date(1294499956278+0800)\/","Name":"张三"}
Copy after login

1 、在后台使用正则表达式对其替换处理。修改JsonHelper:

  using System;
 using SystemCollectionsGeneric;
 using SystemLinq;
 using SystemWeb;
 using SystemRuntimeSerializationJson;
 using SystemIO;
 using SystemText;
 using SystemTextRegularExpressions;
  
 /// <summary>
 /// JSON序列化和反序列化辅助类
 /// </summary>
 public class JsonHelper
 {
  /// <summary>
  /// JSON序列化
  /// </summary>
  public static string JsonSerializer<T>(T t)
  {
   DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
   MemoryStream ms = new MemoryStream();
   serWriteObject(ms, t);
   string jsonString = EncodingUTFGetString(msToArray());
   msClose();
   //替换Json的Date字符串
   string p = @"\\/Date\((\d+)\+\d+\)\\/";
   MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
   Regex reg = new Regex(p);
   jsonString = regReplace(jsonString, matchEvaluator);
   return jsonString;
  }
 
  /// <summary>
  /// JSON反序列化
  /// </summary>
  public static T JsonDeserialize<T>(string jsonString)
  {
   //将"yyyy-MM-dd HHmmss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式
   string p = @"\d{4}-\d{2}-\d{2}\s\d{2}\d{2}\d{2}";
   MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
   Regex reg = new Regex(p);
   jsonString = regReplace(jsonString, matchEvaluator);
   DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
   MemoryStream ms = new MemoryStream(EncodingUTFGetBytes(jsonString));
   T obj = (T)serReadObject(ms);
   return obj;
  }
 
  /// <summary>
  /// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串
  /// </summary>
  private static string ConvertJsonDateToDateString(Match m)
  {
   string result = stringEmpty;
   DateTime dt = new DateTime(1970,1,1);
   dt = dtAddMilliseconds(longParse(mGroups[1]Value));
   dt = dtToLocalTime();
   result = dtToString("yyyy-MM-dd HHmmss");
   return result;
  }
 
  /// <summary>
  /// 将时间字符串转为Json时间
  /// </summary>
  private static string ConvertDateStringToJsonDate(Match m)
  {
   string result = stringEmpty;
   DateTime dt = DateTimeParse(mGroups[0]Value);
   dt = dtToUniversalTime();
   TimeSpan ts = dt - DateTimeParse("1970-01-01");
   result = stringFormat("\\/Date({0}+0800)\\/",tsTotalMilliseconds);
   return result;
  }
 }
Copy after login

序列化Demo:

  Person p = new Person();
 p.Name = "张三";
 p.Age = 28;
 p.LastLoginTime = DateTime.Now; 
 string jsonString = JsonHelper.JsonSerializer<Person>(p);
Copy after login

 运行结果:

{"Age":28,"LastLoginTime":"2011-01-09 01:00:56","Name":"张三"}
Copy after login

反序列化Demo:

string json = "{\"Age\":28,\"LastLoginTime\":\"2011-01-09 00:30:00\",\"Name\":\"张三\"}";
p=JsonHelper.JsonDeserialize<Person>(json);
Copy after login

运行结果:

在后台替换字符串适用范围比较窄,如果考虑到全球化的有多种语言还会更麻烦。

2、利用JavaScript处理   

 function ChangeDateFormat(jsondate) {
  jsondate = jsondate.replace("/Date(", "").replace(")/", "");
  if (jsondate.indexOf("+") > 0) {
   jsondate = jsondate.substring(0, jsondate.indexOf("+"));
  }
  else if (jsondate.indexOf("-") > 0) {
   jsondate = jsondate.substring(0, jsondate.indexOf("-"));
  }
  
  var date = new Date(parseInt(jsondate, 10));
  var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) date.getMonth() + 1;
  var currentDate = date.getDate() < 10 ? "0" + date.getDate() date.getDate();
  return date.getFullYear() + "-" + month + "-" + currentDate;
 }
Copy after login

 简单Demo :

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

结果:

2011-1-8

四、JSON序列化和反序列化集合、字典、数组的处理

 在JSON数据中,所有的集合、字典和数组都表示为数组。

List序列化:

  List<Person> list = new List<Person>()
 {
  new Person(){ Name="张三", Age=28},
  new Person(){ Name="李四", Age=25}
 };
string jsonString = JsonHelper.JsonSerializer<List<Person>>(list);
Copy after login

序列化结果:

"[{\"Age\":28,\"Name\":\"张三\"},{\"Age\":25,\"Name\":\"李四\"}]"
Copy after login

字典不能直接用于JSON,Dictionary字典转化为JSON并不是跟原来的字典格式一致,而是形式以Dictionary的Key作为名称”Key“的值,以Dictionary的Value作为名称为”Value“的值 。如:

  Dictionary<string, string> dic = new Dictionary<string, string>();
 dic.Add("Name", "张三");
 dic.Add("Age", "28");
 string jsonString = JsonHelper.JsonSerializer < Dictionary<string, string>>(dic);
Copy after login

序列化结果:

 "[{\"Key\":\"Name\",\"Value\":\"张三\"},{\"Key\":\"Age\",\"Value\":\"28\"}]"
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

jsonp+json实现AJAX跨域请求

JS基于ajax操作信息的使用

The above is the detailed content of JSON serialization and deserialization implementation methods (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese Mar 05, 2024 pm 02:48 PM

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

How does Java serialization affect performance? How does Java serialization affect performance? Apr 16, 2024 pm 06:36 PM

The impact of serialization on Java performance: The serialization process relies on reflection, which will significantly affect performance. Serialization requires the creation of a byte stream to store object data, resulting in memory allocation and processing costs. Serializing large objects consumes a lot of memory and time. Serialized objects increase load when transmitted over the network.

Quick tips for converting PHP arrays to JSON Quick tips for converting PHP arrays to JSON May 03, 2024 pm 06:33 PM

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.

How does the C++ function library perform serialization and deserialization? How does the C++ function library perform serialization and deserialization? Apr 18, 2024 am 10:06 AM

C++ Library Serialization and Deserialization Guide Serialization: Creating an output stream and converting it to an archive format. Serialize objects into archive. Deserialization: Creates an input stream and restores it from archive format. Deserialize objects from the archive. Practical example: Serialization: Creating an output stream. Create an archive object. Create and serialize objects into the archive. Deserialization: Create an input stream. Create an archive object. Create objects and deserialize them from the archive.

How to use PHP functions to process JSON data? How to use PHP functions to process JSON data? May 04, 2024 pm 03:21 PM

PHP provides the following functions to process JSON data: Parse JSON data: Use json_decode() to convert a JSON string into a PHP array. Create JSON data: Use json_encode() to convert a PHP array or object into a JSON string. Get specific values ​​of JSON data: Use PHP array functions to access specific values, such as key-value pairs or array elements.

See all articles