C#.Net 使用 JsonReader/JsonWriter 高性能解析/生成 Json 文档
Swifter.Json 是由本人编写的高性能且多功能的 Json 解析库。下图是 Swifter.Json 与 .Net 平台上的其他 Json 库性能对比:

在 Swifter.Json 近期更新的 API 中增加了直接构建 JSON 和直接解析 JSON 的方法。下面演示这两个方法如何使用:
1:使用 JsonWriter 直接生成 Json 文档:
using Swifter.Json;
using Swifter.Tools;
using System; public class Demo
{
public static void Main()
{
var jsonWriter = JsonFormatter.CreateJsonWriter(); jsonWriter.WriteBeginObject(); jsonWriter.WritePropertyName("Id");
jsonWriter.WriteInt32(); jsonWriter.WritePropertyName("Name");
jsonWriter.WriteString("Dogwei"); jsonWriter.WriteEndObject(); Console.WriteLine(jsonWriter.HGCache.ToStringEx()); /**
* Output : {"Id":123,"Name":"Dogwei"}
*/
}
}
注意:使用 JsonWriter 时应将 jsonWriter 保存起来,重复使用,这样才能将性能最大化。
2:使用 JsonReader 直接遍历 Json 文档:
using Swifter.Json;
using System;
using System.IO; public class Demo
{
public static void Main()
{
using var textReader = new StringReader("{\"Id\":123,\"Name\":\"Dogwei\"}"); var jsonReader = JsonFormatter.CreateJsonReader(textReader); if (jsonReader.TryReadBeginObject())
{
while (!jsonReader.TryReadEndObject())
{
var name = jsonReader.ReadPropertyName(); switch (name)
{
case "Id":
Console.WriteLine($"{name}: {jsonReader.ReadInt32()}");
break;
case "Name":
Console.WriteLine($"{name}: {jsonReader.ReadString()}");
break;
default:
Console.WriteLine($"{name}: {jsonReader.DirectRead()}");
break;
}
}
} /**
* Output :
* Id: 123
* Name: Dogwei
*/
}
}
3:更简单的遍历 Json 文档:
using Swifter.Json;
using System;
using System.IO; public class Demo
{
public static void Main()
{
using var textReader = new StringReader("[{\"Id\":1,\"Name\":\"Dogwei\"},{\"Id\":2,\"Name\":\"ChenXinwei\"},{\"Id\":3,\"Name\":\"Swifter.Json\"}]"); var jsonReader = JsonFormatter.CreateJsonReader(textReader); foreach (var item in jsonReader.ReadArray())
{
foreach (var pair in item.ReadObject())
{
var name = pair.Key;
var value = pair.Value.DirectRead(); Console.WriteLine($"{name} : {value}");
}
} /**
* Output :
* Id : 1
* Name : Dogwei
* Id : 2
* Name : ChenXinwei
* Id : 3
* Name : Swifter.Json
*/
}
}
注意:JsonReader 是原始提供的是原始解析 Json 的方法,它性能极快,也正因此,它每个读取方法都会偏移游标,不读取就不偏移,解析 Json 时所有的 '值' 都必须读且只读一次!如上例:如果 pair.Value.DirectRead() 调用了两次,或者一次都没调用,那么就会解析出错!
下例做一下简单的性能对比:
using Newtonsoft.Json;
using Swifter.Json;
using System;
using System.Diagnostics;
using System.IO; public class Demo
{
public static void Main()
{
var swifterWriter = JsonFormatter.CreateJsonWriter(); var newtonsoftStringWriter = new StringWriter();
var newtonsoftWriter = new JsonTextWriter(newtonsoftStringWriter); while (true)
{
var stopwatch = Stopwatch.StartNew(); for (int i = ; i < ; i++)
{
newtonsoftWriter.WriteStartObject(); newtonsoftWriter.WritePropertyName("Id");
newtonsoftWriter.WriteValue(); newtonsoftWriter.WritePropertyName("Name");
newtonsoftWriter.WriteValue("Dogwei"); newtonsoftWriter.WriteEndObject(); newtonsoftStringWriter.GetStringBuilder().Length = ;
} Console.WriteLine($"Newtonsoft.Json : {stopwatch.ElapsedMilliseconds}"); stopwatch = Stopwatch.StartNew(); for (int i = ; i < ; i++)
{
swifterWriter.WriteBeginObject(); swifterWriter.WritePropertyName("Id");
swifterWriter.WriteInt32(); swifterWriter.WritePropertyName("Name");
swifterWriter.WriteString("Dogwei"); swifterWriter.WriteEndObject(); swifterWriter.Clear();
} Console.WriteLine($"Swifter.Json : {stopwatch.ElapsedMilliseconds}"); Console.ReadKey();
} /**
* Output:
* Newtonsoft.Json : 197
* Swifter.Json : 64
*/
}
}
using Newtonsoft.Json;
using Swifter.Json;
using System;
using System.Diagnostics;
using System.IO; public class Demo
{
public static void Main()
{
while (true)
{
var stopwatch = Stopwatch.StartNew(); for (int i = ; i < ; i++)
{
var jsonReader = new JsonTextReader(new StringReader("{\"Id\":123,\"Name\":\"Dogwei\"}")); while (jsonReader.Read())
{
if (jsonReader.TokenType == JsonToken.PropertyName)
{
var name = (string)jsonReader.Value; switch (name)
{
case "Id":
jsonReader.ReadAsInt32();
break;
case "Name":
jsonReader.ReadAsString();
break;
default:
jsonReader.Skip();
break;
}
}
}
} Console.WriteLine($"Newtonsoft.Json : {stopwatch.ElapsedMilliseconds}"); stopwatch = Stopwatch.StartNew(); for (int i = ; i < ; i++)
{
var jsonReader = JsonFormatter.CreateJsonReader(new StringReader("{\"Id\":123,\"Name\":\"Dogwei\"}")); if (jsonReader.TryReadBeginObject())
{
while (!jsonReader.TryReadEndObject())
{
var name = jsonReader.ReadPropertyName(); switch (name)
{
case "Id":
jsonReader.ReadInt32();
break;
case "Name":
jsonReader.ReadString();
break;
default:
jsonReader.SkipValue();
break;
}
}
}
} Console.WriteLine($"Swifter.Json : {stopwatch.ElapsedMilliseconds}"); Console.ReadKey();
} /**
* Output:
* Newtonsoft.Json : 759
* Swifter.Json : 161
*/
}
}
特别强调:这两种方式都是提供给有特别需求的用户,普通用户不建议使用,因为使用门槛较高,不利于维护!个人建议是定义模型,然后不管是序列化和反序列化都使用模型!这样在保证性能的情况下,使用也变得简单,易于维护。
最后附上 Swifter.Json 的开源地址:https://github.com/Dogwei/Swifter.Json 希望大家支持一下。
C#.Net 使用 JsonReader/JsonWriter 高性能解析/生成 Json 文档的更多相关文章
- .NET Core和Swagger 生成 Api 文档
测试/生产环境的BUG 这里更新一下在本地调试正常,在INT/PROD上抛错,错误信息为: */**/*.xml(Swagger json file) 文件找不到,在startup 里builder ...
- .NET Core和Swagger 生成 Api 文档转
阅读目录 1.引用 2.打开startup.cs文件 3.设置XML注释 4.运行结果 5.主要问题的解决办法 6.可以自定义UI 前言 最近写了好多Web api, 老大说太乱了,要整理一下,使用S ...
- DOM生成XML文档与解析XML文档(JUNIT测试)
package cn.liuning.test; import java.io.File; import java.io.IOException; import javax.xml.parsers.D ...
- SAX解析和生成XML文档
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本人声明.否则将追究法律责任. 作者: 永恒の_☆ 地址: http://blog.csdn.net/chenghui031 ...
- PHP获取cookie、Token、模拟登录、抓取数据、解析生成json
本文介绍使用PHP获取cookie,获取Token.以及模拟登录.然后抓取数据.最后解析生成json的的过程. 0. 设置Cookie路径 set_time_limit(0); //使用的cookie ...
- 利用Java动态生成 PDF 文档
利用Java动态生成 PDF 文档,则需要开源的API.首先我们先想象需求,在企业应用中,客户会提出一些复杂的需求,比如会针对具体的业务,构建比较典型的具备文档性质的内容,一般会导出PDF进行存档.那 ...
- WebAPI使用多个xml文件生成帮助文档
一.前言 上篇有提到在WebAPI项目内,通过在Nuget里安装(Microsoft.AspNet.WebApi.HelpPage)可以根据注释生成帮助文档,查看代码实现会发现是基于解析项目生成的xm ...
- POI生成WORD文档
h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h ...
- PHP的学习--使用PhpDocumentor 2生成API文档
官网地址:http://www.phpdoc.org/ 项目地址:https://github.com/phpDocumentor/phpDocumentor2 phpDocumentor 2是一个可 ...
随机推荐
- C# params 可变参数使用注意
今天在一个 .NET Core 项目中调用一个自己实现的使用 params 可变参数的方法时触发了 null 引用异常,原以为是方法中没有对参数进行 null 值检查引起的,于是加上 check nu ...
- LeetCode 387: 字符串中的第一个唯一字符 First Unique Character in a String
题目: 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引.如果不存在,则返回 -1. Given a string, find the first non-repeating charact ...
- Linux内核驱动之GPIO子系统API接口概述
1.前言 在嵌入式Linux开发中,对嵌入式SoC中的GPIO进行控制非常重要,Linux内核中提供了GPIO子系统,驱动开发者在驱动代码中使用GPIO子系统提供的API函数,便可以达到对GPIO控制 ...
- 使用JaCoCo Maven插件创建代码覆盖率报告
这篇博客文章描述了我们如何使用JaCoCo Maven插件为单元和集成测试创建代码覆盖率报告. 我们的构建要求如下: 运行测试时,我们的构建必须为单元测试和集成测试创建代码覆盖率报告. 代码覆盖率报告 ...
- 定位表和索引使用的Page
数据存储的基本单元是Page,每个Page是8KB,数据文件(mdf和ndf)占用的硬盘空间,逻辑上按照PageNumber进行划分,也就是说,可以把数据文件看作是PageNumber 从0到n的连续 ...
- python基础(31):进程(一)
1. 什么是进程 进程(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础.在早期面向进程设计的计算机结构中,进程是程序的基本执行 ...
- TreeMap源码分析,看了都说好
概述 TreeMap也是Map接口的实现类,它最大的特点是迭代有序,默认是按照key值升序迭代(当然也可以设置成降序).在前面的文章中讲过LinkedHashMap也是迭代有序的,不过是按插入顺序或访 ...
- Python爬取620首虾米歌曲,揭秘五月天为什么狂吸粉?!
前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: CDA数据分析师 PS:如有需要Python学习资料的小伙伴可以加点 ...
- SpringCloud Gateway拦截器遇到的小坑汇总
很多朋友在使用SpringCloudGateway的时候可能都碰到过以下几个问题 SpringCloudGateway中如何读取Post请求体 private BodyInserter getBody ...
- docker挡板程序实现启动多个实例进程
启动服务: docker-compose restart