c# System.Text.Json 精讲
<p>本文内容来自我写的开源电子书《WoW C#》,现在正在编写中,可以去WOW-Csharp/学习路径总结.md at master · sogeisetsu/WOW-Csharp (github.com)来查看编写进度。预计2021年年底会完成编写,2022年2月之前会完成所有的校对和转制电子书工作,争取能够在2022年将此书上架亚马逊。编写此书的目的是因为目前.NET市场相对低迷,很多优秀的书都是基于.NET framework框架编写的,与现在的.NET 6相差太大,正规的.NET 5学习教程现在几乎只有MSDN,可是MSDN虽然准确优美但是太过琐碎,没有过阅读开发文档的同学容易一头雾水,于是,我就编写了基于.NET 5的《WoW C#》。本人水平有限,欢迎大家去本书的开源仓库sogeisetsu/WOW-Csharp关注、批评、建议和指导。</p><h1 id="json解析">Json解析</h1>
<p>json是一种类似于通过键值对来储存数据的格式,在对数据库进行操作的时候,通常会把类数据转为json格式,然后储存在数据库里面,使用的时候再将json转为类的实例化对象。java的springboot框架的一整套解决方案里面可以通过mybatis和fastjson完成这个操作。在web的前后端数据传输中,一般也是用json作为数据的载体,JavaScript有着对json比较完备的支持。</p>
<h2 id="json格式概述">Json格式概述</h2>
<ul>
<li>
<p>基础</p>
<ol>
<li>概念: JavaScript Object Notation JavaScript对象表示法</li>
</ol>
<ul>
<li>
<p>json现在多用于存储和交换文本信息的语法</p>
</li>
<li>
<p>进行数据的传输</p>
</li>
<li>
<p>JSON 比 XML 更小、更快,更易解析。</p>
</li>
</ul>
<ol start="2">
<li>
<p>语法:</p>
</li>
<li>
<p>基本规则</p>
</li>
</ol>
<pre><code>-数据在名称/值对中:json数据是由键值对构成的
-键用引号(单双都行)引起来,也可以不使用引号
-值得取值类型:
1. 数字(整数或浮点数)
2. 字符串(在双引号中)
3. 逻辑值(true 或 false)
4. 数组(在方括号中) {"persons":[{},{}]}
5. 对象(在花括号中) {"address":{"province":"陕西"....}}
6. null
-数据由逗号分隔:多个键值对由逗号分隔
-花括号保存对象:使用{}定义json 格式
-方括号保存数组:[]
</code></pre>
<ol start="2">
<li><code>JavaScript</code>获取数据:</li>
</ol>
</li>
</ul>
<ol>
<li>
<p>json对象.键名</p>
</li>
<li>
<p>json对象["键名"]</p>
</li>
<li>
<p>数组对象[索引]</p>
</li>
<li>
<p>遍历<img src="https://api2.mubu.com/v3/document_image/ef51d424-5689-4d07-b7b9-928479bec563-6002481.jpg" alt="img" loading="lazy"></p>
</li>
</ol>
<h2 id="解析">解析</h2>
<p>使用 C# 对 JSON 进行序列化和反序列化 - .NET | Microsoft Docs</p>
<p>会用到两个名词,<strong>序列化和反序列化,其中序列化是指将实例对象转换成json格式的字符串,反序列化则是逆向前面序列化的过程。</strong></p>
<p>在序列化的过程中,<strong>默认情况下会只序列化公共读写的属性,可以通过<code>System.Text.Json.Serialization</code>的<code>JsonInclude</code>特性或者<code>JsonSerializerOptions</code>的<code>IncludeFields</code>属性来包含公有字段。通过<code>System.Text.Json.Serialization</code>的<code>JsonInclude</code>特性可以来自定义可以序列化的非公共属性访问器(即属性的访问修饰符为public,但是set访问器和get访问器的任意一方为非public)。</strong>这可能对使用惯了java的人来说不适应,事实上这是一种很合理的序列化要求,默认状况下,序列化器会序列化对象中的所有可读属性,反序列化所有可写属性,这种方式尊重了访问修饰符的作用。<strong>也可用开源的<code>Newtonsoft.Json</code>来序列化非公有属性。</strong>现在很多编程语言(包括.NET)能通过反射来获取私有属性本身就是不合理的,从<code>.NET core</code>能明显的感觉到.NET团队出于安全的考虑在限制反射的使用。</p>
<p>需要用到的<code>namespace</code>:</p>
<pre><code class="language-c#">using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;
</code></pre>
<ul>
<li>用<code>System.Text.Json</code>的<strong><code>JsonSerializer.Serialize</code>方法可以进行序列化</strong>。</li>
<li>用<code>System.Text.Json</code>的<strong><code>JsonSerializer.Deserialize</code>方法可以进行反序列化</strong>。</li>
<li>用<code>System.Text.Json.Serialization</code>可以要序列化的类<strong>添加必要的特性</strong>,比如<code>JsonPropertyName</code>为属性序列化时重命名,再比如<code>JsonInclude</code>来定义序列化时要包含的字段。</li>
<li>用<code>System.Text.Encodings.Web</code>和<code>System.Text.Unicode</code>来让特定的字符集在序列化的时候能够正常序列化而不是被转义成为 <code>\uxxxx</code>,其中 <code>xxxx</code> 为字符的 Unicode 代码。事实上,<strong>默认情况下,序列化程序会转义所有非 ASCII 字符。</strong></li>
</ul>
<h3 id="序列化">序列化</h3>
<p>只将实例化对象转变成json字符串,假设有一个实例化对象<code>weatherForecast</code>,序列化方式如下:</p>
<pre><code class="language-c#">string jsonString = JsonSerializer.Serialize(weatherForecast);
</code></pre>
<h3 id="反序列化">反序列化</h3>
<p>指将json字符串序列化成实例化对象,书接前文,方式如下:</p>
<pre><code class="language-c#">weatherForecast = JsonSerializer.Deserialize<WeatherForecastWithPOCOs>(jsonString);
</code></pre>
<h3 id="jsonserializeroptions"><code>JsonSerializerOptions</code></h3>
<p>可以通过<code>JsonSerializerOptions</code>来指定诸如是否整齐打印和忽略Null值属性等信息。使用方式为将<code>JsonSerializerOptions</code>实例化之后再当作<code>JsonSerializer.Serialize</code>和<code>JsonSerializer.Deserialize</code>的参数。</p>
<p>关于<code>JsonSerializerOptions</code>的属性可以查看如何使用 System.Text.Json 实例化 JsonSerializerOptions | Microsoft Docs</p>
<p>先实例化一个<strong><code>JsonSerializerOptions</code></strong>对象,在<strong>初始化器里面定义各种属性</strong>:</p>
<pre><code class="language-c#">JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions()
{
// 整齐打印
WriteIndented = true,
// 忽略值为Null的属性
IgnoreNullValues = true,
// 设置Json字符串支持的编码,默认情况下,序列化程序会转义所有非 ASCII 字符。 即,会将它们替换为 \uxxxx,其中 xxxx 为字符的 Unicode
// 代码。 可以通过设置Encoder来让生成的josn字符串不转义指定的字符集而进行序列化 下面指定了基础拉丁字母和中日韩统一表意文字的基础Unicode 块
// (U+4E00-U+9FCC)。 基本涵盖了除使用西里尔字母以外所有西方国家的文字和亚洲中日韩越的文字
Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs),
// 反序列化不区分大小写
PropertyNameCaseInsensitive = true,
// 驼峰命名
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
// 对字典的键进行驼峰命名
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
// 序列化的时候忽略null值属性
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
// 忽略只读属性,因为只读属性只能序列化而不能反序列化,所以在以json为储存数据的介质的时候,序列化只读属性意义不大
IgnoreReadOnlyFields = true,
// 不允许结尾有逗号的不标准json
AllowTrailingCommas = false,
// 不允许有注释的不标准json
ReadCommentHandling = JsonCommentHandling.Disallow,
// 允许在反序列化的时候原本应为数字的字符串(带引号的数字)转为数字
NumberHandling = JsonNumberHandling.AllowReadingFromString,
// 处理循环引用类型,比如Book类里面有一个属性也是Book类
ReferenceHandler = ReferenceHandler.Preserve
};
</code></pre>
<p>然后在序列化和反序列化的时候<strong><code>jsonSerializerOptions</code></strong>对象当作参数传给<code>JsonSerializer.Serialize</code>和<code>JsonSerializer.Deserialize</code>:</p>
<pre><code class="language-c#">string jsonBookA = JsonSerializer.Serialize(bookA, jsonSerializerOptions);
// 反序列化
BookA bookA1 = JsonSerializer.Deserialize<BookA>(jsonBookA, jsonSerializerOptions);
</code></pre>
<h4 id="jsonserializeroptions-常用属性概述"><code>JsonSerializerOptions</code> 常用属性概述</h4>
<table>
<thead>
<tr>
<th></th>
<th>作用</th>
<th>值类型</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>WriteIndented</code></td>
<td>整齐打印,将此值设置为true后序列化的json字符串在打印的时候会进行自动缩进和换行。<strong>默认为false。</strong></td>
<td>bool</td>
</tr>
<tr>
<td><code>IgnoreNullValues</code></td>
<td>忽略值为Null的属性。<strong>默认为false。</strong></td>
<td>bool</td>
</tr>
<tr>
<td><code>Encoder</code></td>
<td>设置Json字符串支持的编码,默认情况下,序列化程序会转义所有非 ASCII 字符。 即,会将它们替换为 \uxxxx,其中 xxxx 为字符的 Unicode代码。 <strong>可以通过设置Encoder来让生成的josn字符串不转义指定的字符集而进行序列化</strong>。可设置为<code>Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs)</code>来包含除使用西里尔字母以外所有西方国家的文字和亚洲中日韩越的文字</td>
<td>JavaScriptEncoder</td>
</tr>
<tr>
<td><code>PropertyNameCaseInsensitive</code></td>
<td><strong>反序列化</strong>不区分键的大小写。<strong>默认为false。</strong></td>
<td>bool</td>
</tr>
<tr>
<td><code>PropertyNamingPolicy</code></td>
<td>序列化时属性的命名方式,常用的为<code>JsonNamingPolicy.CamelCase</code>设置成小写字母开头的驼峰命名。</td>
<td>JsonNamingPolicy</td>
</tr>
<tr>
<td><code>DictionaryKeyPolicy</code></td>
<td>序列化时对字典的string键进行小写字母开头的驼峰驼峰命名。</td>
<td>JsonNamingPolicy</td>
</tr>
<tr>
<td><code>DefaultIgnoreCondition</code></td>
<td>指定一个条件,用于确定何时在<strong>序列化或反序列化</strong>过程中忽略具有默认值的属性。 默认值为 Never。常用值为<code>JsonIgnoreCondition.WhenWritingDefault</code>来忽略默认值属性。</td>
<td>JsonIgnoreCondition</td>
</tr>
<tr>
<td><code>IgnoreReadOnlyProperties </code></td>
<td>序列化时忽略只读属性,因为只读属性只能序列化而不能反序列化,所以在以json为储存数据的介质的时候,序列化只读属性意义不大。<strong>默认为false。</strong></td>
<td>bool</td>
</tr>
<tr>
<td><code>AllowTrailingCommas</code></td>
<td>反序列化时,允许结尾有逗号的不标准json,<strong>默认为false。</strong></td>
<td>bool</td>
</tr>
<tr>
<td><code>ReadCommentHandling</code></td>
<td>反序列化时,允许有注释的不标准json,<strong>默认为false。</strong></td>
<td>bool</td>
</tr>
<tr>
<td><code>NumberHandling</code></td>
<td>使用<code>NumberHandling = JsonNumberHandling.AllowReadingFromString</code>可允许在反序列化的时候原本应为数字的字符串(带引号的数字)转为数字</td>
<td>JsonNumberHandling</td>
</tr>
<tr>
<td><code>ReferenceHandler</code></td>
<td>配置在读取和写入 JSON 时如何处理对象引用。使用<code>ReferenceHandler = ReferenceHandler.Preserve</code>仍然会在序列化和反序列化的时候保留引用并处理循环引用。</td>
<td>ReferenceHandler</td>
</tr>
<tr>
<td><code>IncludeFields</code></td>
<td>确定是否在序列化和反序列化期间处理字段。 默认值为 <code>false</code>。</td>
<td>bool</td>
</tr>
</tbody>
</table>
<h3 id="systemtextjsonserialization-特性"><code>System.Text.Json.Serialization</code> 特性</h3>
<p>可以为将要序列化和被反序列化而生成的类的属性和字段添加特性。</p>
<h4 id="jsoninclude-包含特定public字段和非公共属性访问器">JsonInclude 包含特定public字段和非公共属性访问器</h4>
<p>在序列化或反序列化时,使用 JsonSerializerOptions.IncludeFields 全局设置或 特性来包含字段(必须是public),当应用于某个属性时,指示非公共的 getter 和 setter 可用于序列化和反序列化。 不支持非公共属性。</p>
<p>demo:</p>
<pre><code class="language-c#">/// <summary>
/// 时间戳
/// </summary>
public long timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
/// <summary>
/// 书的名称
/// </summary>
public string Name { private get; set; } = "《书名》";
</code></pre>
<h4 id="jsonpropertyname-自定义属性名称">JsonPropertyName 自定义属性名称</h4>
<p>若要设置单个属性的名称,请使用 特性。</p>
<p>此特性设置的属性名称:</p>
<ul>
<li>同时适用于两个方向(序列化和反序列化)。</li>
<li>优先于属性命名策略。</li>
</ul>
<p>demo:</p>
<pre><code class="language-c#">/// <summary>
/// 作者
/// </summary>
public string Author
{
get { return _author; }
set { _author = value; }
}
</code></pre>
<h4 id="jsonignore-忽略单个属性">JsonIgnore 忽略单个属性</h4>
<p>阻止对属性进行<strong>序列化或反序列化。</strong></p>
<p>demo:</p>
<pre><code class="language-c#">/// <summary>
/// 书的出版商
/// </summary>
public string OutCompany { get => _outCompany; set => _outCompany = value; }
</code></pre>
<h4 id="jsonextensiondata-处理溢出-json">JsonExtensionData 处理溢出 JSON</h4>
<p>反序列化时,可能会在 JSON 中收到不是由目标类型的属性表示的数据。可以将这些无法由目标类型的属性表示的数据储存在一个<code>Dictionary<string, JsonElement></code>字典里面,方式如下:</p>
<pre><code class="language-c#">/// <summary>
/// 储存反序列化时候的溢出数据
/// </summary>
public Dictionary<string, JsonElement> ExtensionData { get; set; }
</code></pre>
<h3 id="笔者的选择">笔者的选择</h3>
<p>在笔者的开发经验当中,json用的最多的就是前后端数据传输和数据库储存数据。对<code>jsonSerializerOptions</code>往往会选择这几个选项:</p>
<pre><code class="language-c#">JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions()
{
// 整齐打印
WriteIndented = true,
// 忽略值为Null的属性
IgnoreNullValues = true,
// 设置Json字符串支持的编码,默认情况下,序列化程序会转义所有非 ASCII 字符。 即,会将它们替换为 \uxxxx,其中 xxxx 为字符的 Unicode
// 代码。 可以通过设置Encoder来让生成的josn字符串不转义指定的字符集而进行序列化 下面指定了基础拉丁字母和中日韩统一表意文字的基础Unicode 块
// (U+4E00-U+9FCC)。 基本涵盖了除使用西里尔字母以外所有西方国家的文字和亚洲中日韩越的文字
Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs, UnicodeRanges.CjkSymbolsandPunctuation),
// 反序列化不区分大小写
PropertyNameCaseInsensitive = true,
// 驼峰命名
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
// 对字典的键进行驼峰命名
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
// 忽略只读属性,因为只读属性只能序列化而不能反序列化,所以在以json为储存数据的介质的时候,序列化只读属性意义不大
IgnoreReadOnlyProperties= true,
// 允许在反序列化的时候原本应为数字的字符串(带引号的数字)转为数字
NumberHandling = JsonNumberHandling.AllowReadingFromString
};
</code></pre>
<p>尽量不使用<code>JsonPropertyName</code>特性,对有可能会用到json反序列化的类一定会用到<code>JsonExtensionData</code>特性来储存可能存在的溢出数据。<code>JsonIgnore</code> 和<code>JsonInclude</code>会广泛的使用而不用<code>JsonSerializerOptions</code>的<code>IncludeFields</code>来序列化所有字段。</p>
<h1 id="license">LICENSE</h1>
<p>已将所有引用其他文章之内容清楚明白地标注,其他部分皆为作者劳动成果。对作者劳动成果做以下声明:</p>
<p>copyright © 2021 苏月晟,版权所有。</p>
<p><img alt="知识共享许可协议" style="border-width: 0" src="https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png"><br>本<span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/Text" rel="dct:type">作品</span>由<span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName">苏月晟</span>采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。</p><br><br>
来源:https://www.cnblogs.com/sogeisetsu/p/15618753.html
頁:
[1]