search
HomeWeb Front-endJS TutorialHow to implement serialization and deserialization of Json (with code)

This time I will show you how to implement Json serialization and deserialization (with code). What are the precautions for Json serialization and deserialization? . The following is a practical case. Let’s take a look. take a look.

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate. JSON is a text format that is completely language independent.

Translation: Json [javascript objectrepresentation method], it is a lightweight data exchange format, we can easily read and write it, and it is very Easily transformed and generated by computers, it is completely independent of language.

Json supports the following two data structures:

  1. A collection of key-value pairs--various Programming languages all support this data structure;

  2. A collection of ordered list type values--this includes arrays, sets, vectors, or sequences, etc. wait.

Json has the following expressions

1. Object

A "key/value" in no order. An object starts with curly braces "{" and ends with curly braces "}". After each "key", there is a colon, and commas are used to separate multiple key-value pairs.

For example:

  var user = {"name":"Manas","gender":"Male","birthday":"1987-8-8"}

2. Array

Set the order of values. An array starts with square brackets "[" and ends with square brackets " ]" ends, and all values ​​are separated by commas

For example:

var userlist = [{"user":{"name":"Manas","gender":"Male","birthday":"1987-8-8"}}, 
{"user":{"name":"Mohapatra","Male":"Female","birthday":"1987-7-7"}}]

3. String

Any number of Unicode characters, use quotation marks Mark and separate them with backslashes.

For example:

var userlist = "{\"ID\":1,\"Name\":\"Manas\",\"Address\":\"India\"}"

Okay, after introducing JSON, let’s get down to business.

There are three ways to serialize and deserialize:

  1. ##Use

    JavaScriptSerializerClass

  2. Using

    DataContractJsonSerializerClass

  3. Using JSON.NET class library

Let’s first look at the use of DataContractJsonSerializer

DataContractJsonSerializer class helps us serialize and deserialize Json, he is in the assembly# In the System.Runtime.Serialization.Json namespace under ## System.Runtime.Serialization.dll.

First of all, here, I create a new console program and create a new class Student

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace JsonSerializerAndDeSerializer
{
 [DataContract]
 public class Student
 {
  [DataMember]
  public int ID { get; set; }
  [DataMember]
  public string Name { get; set; }
  [DataMember]
  public int Age { get; set; }
  [DataMember]
  public string Sex { get; set; }
 }
}

Note: Above The contracts [DataMember] and [DataContract] in the Student entity must be added when using DataContractJsonSerializer for serialization and deserialization. It is not necessary to add the other two methods, and it is OK.

The code of our program:

To reference the assembly first, after introducing this namespace

//----------------------------------------------------------------------------------------------
//使用DataContractJsonSerializer方式需要引入的命名空间,在System.Runtime.Serialization.dll.中
using System.Runtime.Serialization.Json;
//--------------------------------------------------------------------------------------------
#region 1.DataContractJsonSerializer方式序列化和反序列化
   Student stu = new Student()
    {
     ID = 1,
     Name = "曹操",
     Sex = "男",
     Age = 1000
    };
   //序列化
   DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Student));
   MemoryStream msObj = new MemoryStream();
   //将序列化之后的Json格式数据写入流中
   js.WriteObject(msObj, stu);
   msObj.Position = 0;
   //从0这个位置开始读取流中的数据
   StreamReader sr = new StreamReader(msObj, Encoding.UTF8);
   string json = sr.ReadToEnd();
   sr.Close();
   msObj.Close();
   Console.WriteLine(json);
   //反序列化
   string toDes = json;
   //string to = "{\"ID\":\"1\",\"Name\":\"曹操\",\"Sex\":\"男\",\"Age\":\"1230\"}";
   using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(toDes)))
   {
    DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(Student));
    Student model = (Student)deseralizer.ReadObject(ms);// //反序列化ReadObject
    Console.WriteLine("ID=" + model.ID);
    Console.WriteLine("Name=" + model.Name);
    Console.WriteLine("Age=" + model.Age);
    Console.WriteLine("Sex=" + model.Sex);
   }
   Console.ReadKey(); 
   #endregion

the result after running is:

Look at using JavaScriptJsonSerializer: JavaScriptSerializer is a class which helps to serialize and deserialize JSON. It is present in namespace System.Web.Script.Serialization which is available in assembly System.Web.Extensions.dll. To serialize a .Net object to JSON string use Serialize method. It's possible to deserialize JSON string to .Net object using Deserialize or DeserializeObject methods. Let's see how to implement serialization and deserialization using JavaScriptSerializer.

Please quote here first

//-----------------------------------------------------------------------------------------
//使用JavaScriptSerializer方式需要引入的命名空间,这个在程序集System.Web.Extensions.dll.中
using System.Web.Script.Serialization;
//----------------------------------------------------------------------------------------
#region 2.JavaScriptSerializer方式实现序列化和反序列化
   Student stu = new Student()
    {
     ID = 1,
     Name = "关羽",
     Age = 2000,
     Sex = "男"
    };
   JavaScriptSerializer js = new JavaScriptSerializer();
   string jsonData = js.Serialize(stu);//序列化
   Console.WriteLine(jsonData);
   ////反序列化方式一:
   string desJson = jsonData;
   //Student model = js.Deserialize<student>(desJson);// //反序列化
   //string message = string.Format("ID={0},Name={1},Age={2},Sex={3}", model.ID, model.Name, model.Age, model.Sex);
   //Console.WriteLine(message);
   //Console.ReadKey(); 
   ////反序列化方式2
   dynamic modelDy = js.Deserialize<dynamic>(desJson); //反序列化
   string messageDy = string.Format("动态的反序列化,ID={0},Name={1},Age={2},Sex={3}",
    modelDy["ID"], modelDy["Name"], modelDy["Age"], modelDy["Sex"]);//这里要使用索引取值,不能使用对象.属性
   Console.WriteLine(messageDy);
   Console.ReadKey(); 
   #endregion</dynamic></student>

结果是:

 

最后看看使用JSON.NET的情况,引入类库:

 

下面的英文,看不懂可略过。。。

Json.NET is a third party library which helps conversion between JSON text and .NET object using the JsonSerializer. The JsonSerializer converts .NET objects into their JSON equivalent text and back again by mapping the .NET object property names to the JSON property names. It is open source software and free for commercial purposes.

The following are some awesome【极好的】 features,
Flexible JSON serializer for converting between .NET objects and JSON.
LINQ to JSON for manually reading and writing JSON.
High performance, faster than .NET's built-in【内嵌】 JSON serializers.
Easy to read JSON.
Convert JSON to and from XML.
Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone.
Let's start learning how to install and implement:

In Visual Studio, go to Tools Menu -> Choose Library Package Manger -> Package Manager Console. It opens a command window where we need to put the following command to install Newtonsoft.Json.

Install-Package Newtonsoft.Json
OR
In Visual Studio, Tools menu -> Manage Nuget Package Manger Solution and type “JSON.NET” to search it online. Here's the figure,

 

//使用Json.NET类库需要引入的命名空间
//-----------------------------------------------------------------------------
using Newtonsoft.Json;
//-------------------------------------------------------------------------
#region 3.Json.NET序列化
   List<student> lstStuModel = new List<student>() 
   {
   
   new Student(){ID=1,Name="张飞",Age=250,Sex="男"},
   new Student(){ID=2,Name="潘金莲",Age=300,Sex="女"}
   };
   //Json.NET序列化
   string jsonData = JsonConvert.SerializeObject(lstStuModel);
   Console.WriteLine(jsonData);
   Console.ReadKey();
   //Json.NET反序列化
   string json = @"{ 'Name':'C#','Age':'3000','ID':'1','Sex':'女'}";
   Student descJsonStu = JsonConvert.DeserializeObject<student>(json);//反序列化
   Console.WriteLine(string.Format("反序列化: ID={0},Name={1},Sex={2},Sex={3}", descJsonStu.ID, descJsonStu.Name, descJsonStu.Age, descJsonStu.Sex));
   Console.ReadKey(); 
   #endregion</student></student></student>

运行之后,结果是:

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

推荐阅读:

使用jquery动态遍历Json对象属性与值步骤详解

jQuery深拷贝Json对象详解(附代码)

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

Statement
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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment