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 文档的更多相关文章

  1. .NET Core和Swagger 生成 Api 文档

    测试/生产环境的BUG 这里更新一下在本地调试正常,在INT/PROD上抛错,错误信息为: */**/*.xml(Swagger json file) 文件找不到,在startup 里builder ...

  2. .NET Core和Swagger 生成 Api 文档转

    阅读目录 1.引用 2.打开startup.cs文件 3.设置XML注释 4.运行结果 5.主要问题的解决办法 6.可以自定义UI 前言 最近写了好多Web api, 老大说太乱了,要整理一下,使用S ...

  3. DOM生成XML文档与解析XML文档(JUNIT测试)

    package cn.liuning.test; import java.io.File; import java.io.IOException; import javax.xml.parsers.D ...

  4. SAX解析和生成XML文档

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本人声明.否则将追究法律责任. 作者: 永恒の_☆ 地址: http://blog.csdn.net/chenghui031 ...

  5. PHP获取cookie、Token、模拟登录、抓取数据、解析生成json

    本文介绍使用PHP获取cookie,获取Token.以及模拟登录.然后抓取数据.最后解析生成json的的过程. 0. 设置Cookie路径 set_time_limit(0); //使用的cookie ...

  6. 利用Java动态生成 PDF 文档

    利用Java动态生成 PDF 文档,则需要开源的API.首先我们先想象需求,在企业应用中,客户会提出一些复杂的需求,比如会针对具体的业务,构建比较典型的具备文档性质的内容,一般会导出PDF进行存档.那 ...

  7. WebAPI使用多个xml文件生成帮助文档

    一.前言 上篇有提到在WebAPI项目内,通过在Nuget里安装(Microsoft.AspNet.WebApi.HelpPage)可以根据注释生成帮助文档,查看代码实现会发现是基于解析项目生成的xm ...

  8. POI生成WORD文档

    h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h ...

  9. PHP的学习--使用PhpDocumentor 2生成API文档

    官网地址:http://www.phpdoc.org/ 项目地址:https://github.com/phpDocumentor/phpDocumentor2 phpDocumentor 2是一个可 ...

随机推荐

  1. oracle--共享磁盘挂载

    01,查看挂载的磁盘 [root@SHLPDBWX01 ~]# fdisk -l Disk /dev/sda: bytes heads, sectors/track, cylinders Units ...

  2. Samba基础配置

    本文环境:CentOS 7 简介 在UNIX-like之间共享文件系统主要是通过NFS实现的,而Windows之间共享文件系统主要是通过基于NetBIOS的网上邻居实现的,1984年Andrew Tr ...

  3. Shell脚本中的while getopts用法小结

    getpots是Shell命令行参数解析工具,旨在从Shell Script的命令行当中解析参数.getopts被Shell程序用来分析位置参数,option包含需要被识别的选项字符,如果这里的字符后 ...

  4. Linux进程和计划任务实践

    1.显示统计占用系统内存最多的进程,并排序. 方法一 [root@test ~]#ps aux --sort=%mem USER PID %CPU %MEM VSZ RSS TTY STAT STAR ...

  5. hibernate中的merge()方法

    Hibernate提供有save().persist().savaOrUpdate()和merge()等方法来提供插入数据的功能.前三者理解起来较后者容易一些,而merge()方法从api中的介绍就可 ...

  6. GO Slice

    一.切片(Slice) 1.1 什么是切片 Go 语言切片是对数组的抽象. Go 数组的长度不可改变,在特定场景中这样的集合就不太适用,Go中提供了一种灵活,功能强悍的内置类型切片("动态数 ...

  7. C# MediaPlayer

    using System.Windows.Media; using Newtonsoft.Json; using System.ComponentModel; namespace ConsoleApp ...

  8. swoole 内存泄露的问题有没有好的办法解决

     在传统的web开发模式中,我们知道,每一次php请求,都要经过php文件从磁盘上读取.初始化.词法解析.语法解析.编译等过程,而且还要与nginx或者apache通信,如果再涉及数据库的交互,还要再 ...

  9. tornado中传递参数的几种方式

    方法一 :tornado路由可以使用正则表达式中的子表达式传递url参数.比如:(r"/member//(\w*)/([01]*)", MemberHandler)匹配以后,tor ...

  10. 邮Z速递物流,让用户密码在网络中遨游

    " 最近分析快递行业的APP上瘾了,求解救." 邮政作为快递行业一个傻大黑的存在,一直很奇怪,我一直在纳闷,邮政和EMS到底是不是一家,在很多网点,它们是一体的存在,但很多东西,又 ...