• 在C#中,Json的序列化和反序列化的几种方式总结


    https://www.cnblogs.com/caofangsheng/p/5687994.html
    序列化:其一:json 数据格式字符串转换为对象。对象转换为json数据格式字符串。
    序列化:其二:对象转换为文件二进制数组,二进制文件数组读取出成为对象。

    在这篇文章中,我们将会学到如何使用C#,来序列化对象成为Json格式的数据,以及如何反序列化Json数据到对象。

    • 什么是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. 

    翻译:Json【javascript对象表示方法】,它是一个轻量级的数据交换格式,我们可以很简单的来读取和写它,并且它很容易被计算机转化和生成,它是完全独立于语言的。

     

    Json支持下面两种数据结构:

    • 键值对的集合--各种不同的编程语言,都支持这种数据结构;
    • 有序的列表类型值的集合--这其中包含数组,集合,矢量,或者序列,等等。

    Json有下面几种表现形式

         1.对象

      一个没有顺序的“键/值”,一个对象以花括号“{”开始,并以花括号"}"结束,在每一个“键”的后面,有一个冒号,并且使用逗号来分隔多个键值对。例如:

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

         2.数组

    设置值的顺序,一个数组以中括号"["开始,并以中括号"]"结束,并且所有的值使用逗号分隔,例如:

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

         3.字符串

    任意数量的Unicode字符,使用引号做标记,并使用反斜杠来分隔。例如:

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

    好了,介绍完JSON,现在说正题,我们事先序列化和反序列化有三种方式:

    1.使用JavaScriptSerializer类

    2.使用DataContractJsonSerializer类

    3.使用JSON.NET类库

     

    我们先来看看使用 DataContractJsonSerializer的情况

    DataContractJsonSerializer类帮助我们序列化和反序列化Json,他在程序集 System.Runtime.Serialization.dll下的System.Runtime.Serialization.Json命名空间里。

     

    首先,这里,我新建一个控制台的程序,新建一个类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; }

      <span style="color: rgba(128, 0, 0, 1)">  [DataMember]
       </span></span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">string</span> Name { <span style="color: rgba(0, 0, 255, 1)">get</span>; <span style="color: rgba(0, 0, 255, 1)">set</span><span style="color: rgba(0, 0, 0, 1)">; }
    
       <span style="color: rgba(128, 0, 0, 1)"> [DataMember]
       </span></span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span> Age { <span style="color: rgba(0, 0, 255, 1)">get</span>; <span style="color: rgba(0, 0, 255, 1)">set</span><span style="color: rgba(0, 0, 0, 1)">; }
    
       <span style="color: rgba(128, 0, 0, 1)"> [DataMember]
       </span></span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">string</span> Sex { <span style="color: rgba(0, 0, 255, 1)">get</span>; <span style="color: rgba(0, 0, 255, 1)">set</span><span style="color: rgba(0, 0, 0, 1)">; }
    }
    

    }

    复制代码

    注意:上面的Student实体中的契约 [DataMember],[DataContract],是使用DataContractJsonSerializer序列化和反序列化必须要加的,对于其他两种方式不必加,也可以的。

    我们程序的代码:

    要先引用程序集,在引入这个命名空间

    //----------------------------------------------------------------------------------------------
    //使用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);
    
            </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">反序列化</span>
            <span style="color: rgba(0, 0, 255, 1)">string</span> toDes =<span style="color: rgba(0, 0, 0, 1)"> json;
            </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">string to = "{"ID":"1","Name":"曹操","Sex":"男","Age":"1230"}";</span>
            <span style="color: rgba(0, 0, 255, 1)">using</span> (<span style="color: rgba(0, 0, 255, 1)">var</span> ms = <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> MemoryStream(Encoding.Unicode.GetBytes(toDes)))
            {
                DataContractJsonSerializer deseralizer </span>= <span style="color: rgba(0, 0, 255, 1)">new</span> DataContractJsonSerializer(<span style="color: rgba(0, 0, 255, 1)">typeof</span><span style="color: rgba(0, 0, 0, 1)">(Student));
                Student model </span>= (Student)deseralizer.ReadObject(ms);<span style="color: rgba(0, 128, 0, 1)">//</span> <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">反序列化ReadObject</span>
                Console.WriteLine(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">ID=</span><span style="color: rgba(128, 0, 0, 1)">"</span> +<span style="color: rgba(0, 0, 0, 1)"> model.ID);
                Console.WriteLine(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">Name=</span><span style="color: rgba(128, 0, 0, 1)">"</span> +<span style="color: rgba(0, 0, 0, 1)"> model.Name);
                Console.WriteLine(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">Age=</span><span style="color: rgba(128, 0, 0, 1)">"</span> +<span style="color: rgba(0, 0, 0, 1)"> model.Age);
                Console.WriteLine(</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">Sex=</span><span style="color: rgba(128, 0, 0, 1)">"</span> +<span style="color: rgba(0, 0, 0, 1)"> model.Sex);
            }
            Console.ReadKey(); 
            </span><span style="color: rgba(0, 0, 255, 1)">#endregion</span></span></pre>
    
    复制代码

    运行之后结果是:

     

    再看看使用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<T> or DeserializeObject methods. Let's see how to implement serialization and deserialization using JavaScriptSerializer.

    这里要先引用

    //-----------------------------------------------------------------------------------------
    //使用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 </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> JavaScriptSerializer();
            </span><span style="color: rgba(0, 0, 255, 1)">string</span> jsonData = js.Serialize(stu);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">序列化</span>
    

    Console.WriteLine(jsonData);

            </span><span style="color: rgba(128, 128, 128, 1)">///</span><span style="color: rgba(0, 128, 0, 1)">/反序列化方式一:</span>
            <span style="color: rgba(0, 0, 255, 1)">string</span> desJson =<span style="color: rgba(0, 0, 0, 1)"> jsonData;
            </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">Student model = js.Deserialize&lt;Student&gt;(desJson);</span><span style="color: rgba(0, 128, 0, 1)">//</span> <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">反序列化
            </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">string message = string.Format("ID={0},Name={1},Age={2},Sex={3}", model.ID, model.Name, model.Age, model.Sex);
            </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">Console.WriteLine(message);
            </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">Console.ReadKey(); </span>
    
    
            <span style="color: rgba(128, 128, 128, 1)">///</span><span style="color: rgba(0, 128, 0, 1)">/反序列化方式2</span>
            <span style="color: rgba(0, 0, 255, 1)">dynamic</span> modelDy = js.Deserialize&lt;<span style="color: rgba(0, 0, 255, 1)">dynamic</span>&gt;(desJson); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">反序列化</span>
            <span style="color: rgba(0, 0, 255, 1)">string</span> messageDy = <span style="color: rgba(0, 0, 255, 1)">string</span>.Format(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">动态的反序列化,ID={0},Name={1},Age={2},Sex={3}</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">,
                modelDy[</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">ID</span><span style="color: rgba(128, 0, 0, 1)">"</span>], modelDy[<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">Name</span><span style="color: rgba(128, 0, 0, 1)">"</span>], modelDy[<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">Age</span><span style="color: rgba(128, 0, 0, 1)">"</span>], modelDy[<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">Sex</span><span style="color: rgba(128, 0, 0, 1)">"</span>]);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">这里要使用索引取值,不能使用对象.属性</span>
    

    Console.WriteLine(messageDy);
    Console.ReadKey();
    #endregion

    复制代码

     

    结果是:

     

    最后看看使用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>() 
                {
    
            </span><span style="color: rgba(0, 0, 255, 1)">new</span> Student(){ID=<span style="color: rgba(128, 0, 128, 1)">1</span>,Name=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">张飞</span><span style="color: rgba(128, 0, 0, 1)">"</span>,Age=<span style="color: rgba(128, 0, 128, 1)">250</span>,Sex=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">男</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">},
            </span><span style="color: rgba(0, 0, 255, 1)">new</span> Student(){ID=<span style="color: rgba(128, 0, 128, 1)">2</span>,Name=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">潘金莲</span><span style="color: rgba(128, 0, 0, 1)">"</span>,Age=<span style="color: rgba(128, 0, 128, 1)">300</span>,Sex=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">女</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">}
            };
    
            </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">Json.NET序列化</span>
            <span style="color: rgba(0, 0, 255, 1)">string</span> jsonData =<span style="color: rgba(0, 0, 0, 1)"> JsonConvert.SerializeObject(lstStuModel);
    
            Console.WriteLine(jsonData);
            Console.ReadKey();
    
    
            </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">Json.NET反序列化</span>
            <span style="color: rgba(0, 0, 255, 1)">string</span> json = <span style="color: rgba(128, 0, 0, 1)">@"</span><span style="color: rgba(128, 0, 0, 1)">{ 'Name':'C#','Age':'3000','ID':'1','Sex':'女'}</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">;
            Student descJsonStu </span>= JsonConvert.DeserializeObject&lt;Student&gt;(json);<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">反序列化</span>
            Console.WriteLine(<span style="color: rgba(0, 0, 255, 1)">string</span>.Format(<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">反序列化: ID={0},Name={1},Sex={2},Sex={3}</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">, descJsonStu.ID, descJsonStu.Name, descJsonStu.Age, descJsonStu.Sex));
            Console.ReadKey(); 
            </span><span style="color: rgba(0, 0, 255, 1)">#endregion</span></span></pre>
    
    复制代码

    运行之后,结果是:

     总结:最后还是尽量使用JSON.NET来序列化和反序列化,性能好。

    In this article we discussed about how many ways we can implement serialization/deserialization in C#. However JSON.NET wins over other implementations because it facilitates more functionality of JSON validation, JSON schema, LINQ to JSON etc. So use JSON.NET always.

     

     

     

     

     

  • 相关阅读:
    两种数组,注意用法
    PD 导出数据库结构
    获取随机金额:上限下限都要取到
    mysql常用语句
    SQL替换字符串、条件查询
    jtopo树结构方法积累
    jtopo 学习
    .net C# SortedList用法
    .net C# List用法
    .Net中C# Dictionary 用法(转)
  • 原文地址:https://www.cnblogs.com/sunny3158/p/14341758.html
Copyright © 2020-2023  润新知