DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  4737 随笔 :: 2 文章 :: 542 评论 :: 1615万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

1. 正文

nlohmann/json是一个c++的读写json的组件,号称使用现代c++范式写的。简单看了一下,这个组件确实包含了很多cpp11以上的特性,在vs2015及一下的版本甚至没办法正常编译。要正常使用需要vs2017及以上版本才行。

在使用过程中,遇到了一个问题是没办法保持插入的顺序,每个插入的键值对会按照字符串的顺序排列的,因为其内部用到了std:map。查看了github的主页说明,是这么说的:

by default, the library does not preserve the insertion order of object elements. this is standards-compliant, as the json standard defines objects as "an unordered collection of zero or more name/value pairs". if you do want to preserve the insertion order, you can specialize the object type with containers like tsl::ordered_map (integration) or nlohmann::fifo_map (integration).

这段话的意思是json标准的定义是零个或多个键值对对的无序集合,如果要保证插入顺序,可以使用tsl::ordered_map(integration)或nlohmann::fifo_map(integration)等容器专门化对象类型。nlohmann::fifo_map同样在github上找到,“专门化对象类型”的意思是nlohmann/json组件内部用到了很多std容器,只需要将其替换成可以保存插入顺序的容器就可以了,也就是nlohmann::fifo_map。

重新找了一些英文资料,最终找到的解决方案如下:

%ignore_pre_1%

运行结果如下所示,可以看到输出的json不再是字符串顺序而是插入顺序:

使用NlohmannJson写JSON保留插入顺序
posted on   DoubleLi  阅读(429)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2012-12-30 我的 VC++ 常见错误问题解决办法
2011-12-30 C#对象的浅拷贝,深拷贝及利用序列化等多种方式实现深拷贝
点击右上角即可分享
微信分享提示