用c#自己实现一个简单的JSON解析器
<h2 id="一json格式介绍">一、JSON格式介绍</h2><ul>
<li>JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。相对于另一种数据交换格式 XML,JSON 有着很多优点。例如易读性更好,占用空间更少等。在 web 应用开发领域内,得益于 JavaScript 对 JSON 提供的良好支持,JSON 要比 XML 更受开发人员青睐。所以作为开发人员,如果有兴趣的话,还是应该深入了解一下 JSON 相关的知识。本着探究 JSON 原理的目的,我将会在这篇文章中详细向大家介绍一个简单的JSON解析器的解析流程和实现细节。由于 JSON 本身比较简单,解析起来也并不复杂。所以如果大家感兴趣的话,在看完本文后,不妨自己动手实现一个 JSON 解析器。好了,其他的话就不多说了,接下来让我们移步到重点章节吧。</li>
<li><strong>在线JOSN校验格式化工具</strong> 如果在解析字符串的时候,拿不准这个是不是正确的JOSN,你可以在这个上面测试一下,有利于对自己代码的测试</li>
</ul>
<h2 id="二解析原理介绍">二、解析原理介绍</h2>
<ul>
<li>解析对象<code>{}</code>
<ul>
<li>对象结构是<code>{"Key":[值]}</code>的格式,所以先解析到Key字符串,将Key解析出来,然后在解析到值,因为值有可能是【<code>字符串</code>、<code>值类型</code>、<code>布尔类型</code>、<code>对象</code>、<code>数组</code>、<code>null</code>】所以需要根据前缀得到类型,并调用相应的解析方法,循环解析到“}”对象结尾</li>
</ul>
</li>
<li>解析数组<code>[]</code>
<ul>
<li>对象的结构是<code>[[值],[值]]</code>,因为值有可能是【<code>字符串</code>、<code>值类型</code>、<code>布尔类型</code>、<code>对象</code>、<code>数组</code>、<code>null</code>】所以需要根据前缀得到类型,并调用相应的解析方法,循环解析到<code>]</code>数组结尾</li>
</ul>
</li>
<li>解析字符串
<ul>
<li>循环解析,需要判断是否遇到转义符<code>\</code>如果遇到,当前字符的下一个字符将是作为普通字符存入结果,如果遇到非转义的 <code>"</code> 字符则退出字符串读取方法,并返回结果</li>
</ul>
</li>
<li>解析值类型
<ul>
<li>循环拉取<code></code>包括<code>.</code>符号,然后调用转换成double类型方法</li>
</ul>
</li>
<li>解析布尔类型
<ul>
<li>转判断是 <code>true</code> 还是 <code>false</code></li>
</ul>
</li>
<li>解析<code>null</code>
<ul>
<li>转判断是否为 <code>null</code></li>
</ul>
</li>
</ul>
<h3 id="解析元素流程图">解析元素流程图</h3>
<p><img src="https://img2020.cnblogs.com/blog/1988850/202007/1988850-20200720134913661-345556756.png" alt="解析元素流程图" loading="lazy"></p>
<h3 id="解析方法列表">解析方法列表</h3>
<table>
<thead>
<tr>
<th style="text-align: left">方法名</th>
<th style="text-align: left">方法作用</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left"><code>AnalysisJson</code></td>
<td style="text-align: left">解析JSON字符串为C#数据结构</td>
</tr>
<tr>
<td style="text-align: left"><code>AnalysisJsonObject</code></td>
<td style="text-align: left">解析JSON字符串为对象结构</td>
</tr>
<tr>
<td style="text-align: left"><code>AnalysisJsonArray</code></td>
<td style="text-align: left">解析JSON字符串为数组结构</td>
</tr>
<tr>
<td style="text-align: left"><code>ReadElement</code></td>
<td style="text-align: left">读取出一个JSON结构</td>
</tr>
<tr>
<td style="text-align: left"><code>ReadJsonNumber</code></td>
<td style="text-align: left">读取出一个值类型结构</td>
</tr>
<tr>
<td style="text-align: left"><code>ReadJsonNull</code></td>
<td style="text-align: left">读取出一个<code>null</code>结构</td>
</tr>
<tr>
<td style="text-align: left"><code>ReadJsonFalse</code></td>
<td style="text-align: left">读取出一个<code>false</code>结构</td>
</tr>
<tr>
<td style="text-align: left"><code>ReadJsonTrue</code></td>
<td style="text-align: left">读取出一个<code>true</code>结构</td>
</tr>
<tr>
<td style="text-align: left"><code>ReadString</code></td>
<td style="text-align: left">读取出一个字符串结构</td>
</tr>
<tr>
<td style="text-align: left"><code>ReadToNonBlankIndex</code></td>
<td style="text-align: left">读取到非空白字符下标位置</td>
</tr>
</tbody>
</table>
<h3 id="例1-解析json">例1 解析JSON</h3>
<pre><code class="language-javascript">{"Name":"张三","Age":18}
</code></pre>
<ul>
<li>1.解析第一个字符<code>{</code>发现是JSON对象结构,调用<code>AnalysisJsonObject</code>方法来解析JSON对象格式</li>
<li>2.解析对象的方法开始循环解析 Key-Value结构直到<code>}</code>对象尾部字符
<ul>
<li>先解析Key结构调用 <code>ReadString</code>来进行解析出Key字符串从而得到<code>Name</code>这个值</li>
<li>然后解析Value因为值可能是任意结构所以调用<code>ReadElement</code>来解析出一个JSON结构
<ul>
<li>读取第一个字符得到<code>"</code>从而知道这个Value是一个字符串,调用方法<code>ReadString</code>来读取到这个Value的值<code>张三</code></li>
</ul>
</li>
<li>读取下一个字符发现不是JSON对象的结尾字符<code>}</code>是<code>,</code>字符代表下面还存在一个Key-Value结构,继续读取</li>
<li>先解析Key结构调用 <code>ReadString</code>来进行解析出Key字符串从而得到<code>Age</code>这个值</li>
<li>然后解析Value因为值可能是任意结构所以调用<code>ReadElement</code>来解析出一个JSON结构
<ul>
<li>读取第一个字符发现是<code>1</code>是数字,代表下面的这个结构是数值类型调用方法<code>ReadJsonNumber</code>来读取数值类型</li>
</ul>
</li>
<li>读取下一个字符发现是<code>}</code>是JSON对象的结尾字符,退出JSON对象解析,返回解析的JSON对象结构实例</li>
</ul>
</li>
</ul>
<h3 id="例2-解析json">例2 解析JSON</h3>
<pre><code class="language-javascript">[{"科目":"语文","成绩":99}]
</code></pre>
<ul>
<li>1.解析第一个字符<code>[</code>发现是JSON数组结构,调用方法<code>AnalysisJsonArray</code>方法来解析出JSON数组结构
<ul>
<li>解析循环解析JSON数据结构直到遇到<code>]</code>数组结构结尾字符
<ul>
<li>因为数组中每个元素都是可能是任意类型数据,所以调用<code>ReadElement</code>方法来解析值</li>
<li>读取值的第一个字符<code>{</code>发现是JSON对象类型调用<code>AnalysisJsonObject</code>方法解析JSON对象
<ul>
<li>先解析Key结构调用 <code>ReadString</code>来进行解析出Key字符串从而得到<code>科目</code>这个值</li>
<li>然后解析Value因为值可能是任意结构所以调用<code>ReadElement</code>来解析出一个JSON结构
<ul>
<li>读取第一个字符得到<code>"</code>从而知道这个Value是一个字符串,调用方法<code>ReadString</code>来读取到这个Value的值<code>语文</code></li>
</ul>
</li>
<li>读取下一个字符发现不是JSON对象的结尾字符<code>}</code>是<code>,</code>字符代表下面还存在一个Key-Value结构,继续读取</li>
<li>先解析Key结构调用 <code>ReadString</code>来进行解析出Key字符串从而得到<code>成绩</code>这个值</li>
<li>然后解析Value因为值可能是任意结构所以调用<code>ReadElement</code>来解析出一个JSON结构
<ul>
<li>读取第一个字符发现是<code>9</code>是数字,代表下面的这个结构是数值类型调用方法<code>ReadJsonNumber</code>来读取数值类型</li>
</ul>
</li>
<li>读取下一个字符发现是<code>}</code>是JSON对象的结尾字符,退出JSON对象解析,返回解析的JSON对象结构实例</li>
</ul>
</li>
<li>读取下一个字符发现是<code>]</code>JSON数组的结尾,退出解析JSON数组,返回解析的JSON数组结构实例</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="三代码实现">三、代码实现</h2>
<pre><code class="language-csharp"> /// <summary>
/// JSON解析类型
/// </summary>
public static class JsonConvert
{
/// <summary>
/// 解析JSON
/// </summary>
/// <param name="text">待解析的JSON字符串</param>
/// <returns>解析完成的JSON结构对象</returns>
public static JsonElement AnalysisJson(string text)
{
var index = 0;
//读取到非空白字符
ReadToNonBlankIndex(text, ref index);
if (text == '[')
//解析数组
return AnalysisJsonArray(text, ref index);
//解析对象
return AnalysisJsonObject(text, ref index);
}
/// <summary>
/// 解析JSON对象
/// </summary>
/// <param name="text">JSON字符串</param>
/// <param name="index">开始索引位置</param>
/// <returns>JSON对象</returns>
private static JsonObject AnalysisJsonObject(string text, ref int index)
{
var jsonArray = new JsonObject();
do
{
ReadToNonBlankIndex(text, ref index);
if (text != '"') throw new JsonAnalysisException($"不能识别的字符“{text}”!应为“\"”", index);
index++;
//读取字符串
var name = ReadString(text, ref index);
if (jsonArray.ContainsKey(name)) throw new JsonAnalysisException($"已经添加键值:“{name}”", index);
ReadToNonBlankIndex(text, ref index);
if (text != ':') throw new JsonAnalysisException($"不能识别的字符“{text}”!", index);
index++;
ReadToNonBlankIndex(text, ref index);
//读取下一个Element
jsonArray.Add(name, ReadElement(text, ref index));
//读取到非空白字符
ReadToNonBlankIndex(text, ref index);
var ch = text;
if (ch == '}') break;
if (ch != ',') throw new JsonAnalysisException($"不能识别的字符“{text}”!", index - 1);
} while (true);
return jsonArray;
}
/// <summary>
/// 解析JSON数组
/// </summary>
/// <param name="text">JSON字符串</param>
/// <param name="index">开始索引位置</param>
/// <returns>JSON数组</returns>
private static JsonArray AnalysisJsonArray(string text, ref int index)
{
var jsonArray = new JsonArray();
do
{
ReadToNonBlankIndex(text, ref index);
//读取下一个Element
jsonArray.Add(ReadElement(text, ref index));
//读取到非空白字符
ReadToNonBlankIndex(text, ref index);
var ch = text;
if (ch == ']') break;
if (ch != ',') throw new JsonAnalysisException($"不能识别的字符“{text}”!", index - 1);
} while (true);
return jsonArray;
}
/// <summary>
/// 读取JSONElement
/// </summary>
/// <param name="text">字符串</param>
/// <param name="index">开始下标</param>
/// <returns>下一个Element</returns>
private static JsonElement ReadElement(string text, ref int index)
{
switch (text)
{
case '[':
return AnalysisJsonArray(text, ref index);
case '{':
return AnalysisJsonObject(text, ref index);
case '"':
return new JsonString(ReadString(text, ref index));
case 't':
return ReadJsonTrue(text, ref index);
case 'f':
return ReadJsonFalse(text, ref index);
case 'n':
return ReadJsonNull(text, ref index);
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return ReadJsonNumber(text, ref index);
default:
throw new JsonAnalysisException($"未知Element“{text}”应该为【[、{{、\"、true、false、null】",
index - 1);
}
}
/// <summary>
/// 读取值类型
/// </summary>
/// <param name="text">JSON字符串</param>
/// <param name="index">开始索引</param>
/// <returns>JSON数值类型</returns>
private static JsonNumber ReadJsonNumber(string text, ref int index)
{
var i = index;
while (i < text.Length && char.IsNumber(text) || text == '.') i++;
if (double.TryParse(text.Substring(index - 1, i - index + 1), out var value))
{
index = i;
return new JsonNumber(value);
}
throw new JsonAnalysisException("不能识别的数字类型!", i);
}
/// <summary>
/// 读取NULL
/// </summary>
/// <param name="text">JSON字符串</param>
/// <param name="index">开始索引</param>
/// <returns>读取NULL</returns>
private static JsonNull ReadJsonNull(string text, ref int index)
{
if (text == 'u' &&
text == 'l' &&
text == 'l')
{
return new JsonNull();
}
throw new JsonAnalysisException("读取null出错!", index - 1);
}
/// <summary>
/// 读取FALSE
/// </summary>
/// <param name="text">JSON字符串</param>
/// <param name="index">开始索引</param>
/// <returns>布尔值-假</returns>
private static JsonBoolean ReadJsonFalse(string text, ref int index)
{
if (text == 'a' &&
text == 'l' &&
text == 's' &&
text == 'e')
{
return new JsonBoolean(false);
}
throw new JsonAnalysisException("读取布尔值出错!", index - 1);
}
/// <summary>
/// 读取TRUE
/// </summary>
/// <param name="text">JSON字符串</param>
/// <param name="index">开始索引</param>
/// <returns>布尔值-真</returns>
private static JsonBoolean ReadJsonTrue(string text, ref int index)
{
if (text == 'r' &&
text == 'u' &&
text == 'e')
{
return new JsonBoolean(true);
}
throw new JsonAnalysisException("读取布尔值出错!", index - 1);
}
/// <summary>
/// 读取字符串
/// </summary>
/// <param name="text">JSON字符串</param>
/// <param name="index">开始索引</param>
/// <returns>字符串值</returns>
private static string ReadString(string text, ref int index)
{
var value = new StringBuilder();
while (index < text.Length)
{
var c = text;
//判断是否是转义字符
if (c == '\\')
{
value.Append('\\');
if (index >= text.Length)
throw new JsonAnalysisException("未知的结尾!", index - 1);
c = text;
value.Append(c);
if (c == 'u')
{
for (int i = 0; i < 4; i++)
{
c = text;
if (IsHex(c))
{
value.Append(c);
}
else
{
throw new JsonAnalysisException("不是有效的Unicode字符!", index - 1);
}
}
}
}
else if (c == '"')
{
break;
}
else if (c == '\r' || c == '\n')
{
throw new JsonAnalysisException("传入的JSON字符串内容中不允许有换行!", index - 1);
}
else
{
value.Append(c);
}
}
return value.ToString();
}
/// <summary>
/// 判断是否为16进制字符
/// </summary>
private static bool IsHex(char c)
{
return c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F';
}
/// <summary>
/// 读取到非空白字符
/// </summary>
/// <param name="text">字符串</param>
/// <param name="index">开始下标</param>
/// <returns>非空白字符下标</returns>
private static void ReadToNonBlankIndex(string text, ref int index)
{
while (index < text.Length && char.IsWhiteSpace(text)) index++;
}
}
</code></pre>
<h3 id="完整demo代码下载">完整DEMO代码下载</h3>
<p>Github项目地址(会持续更新):DEMO代码</p><br><br>
来源:https://www.cnblogs.com/liuzhenliang/p/AnalysisJson.html
頁:
[1]