本文首发于个人博客https://kezunlin.me/post/f3c3eb8/,欢迎阅读最新内容!

tutorial to use nlohmann json for serializing data with modern cpp

Guide

include

#include <nlohmann/json.hpp>

// for convenience
using json = nlohmann::json;

compile with

-std=c++11

CMakeLists.txt

# CMakeLists.txt
find_package(nlohmann_json 3.2.0 REQUIRED)
...
add_library(foo ...)
...
target_link_libraries(foo PRIVATE nlohmann_json::nlohmann_json)

Usage

json demo

{
"pi": 3.141,
"happy": true,
"name": "Niels",
"nothing": null,
"answer": {
"everything": 42
},
"list": [1, 0, 2],
"object": {
"currency": "USD",
"value": 42.99
}
}

with code

// create an empty structure (null)
json j; // add a number that is stored as double (note the implicit conversion of j to an object)
j["pi"] = 3.141; // add a Boolean that is stored as bool
j["happy"] = true; // add a string that is stored as std::string
j["name"] = "Niels"; // add another null object by passing nullptr
j["nothing"] = nullptr; // add an object inside the object
j["answer"]["everything"] = 42; // add an array that is stored as std::vector (using an initializer list)
j["list"] = { 1, 0, 2 }; // add another object (using an initializer list of pairs)
j["object"] = { {"currency", "USD"}, {"value", 42.99} }; // instead, you could also write (which looks very similar to the JSON above)
json j2 = {
{"pi", 3.141},
{"happy", true},
{"name", "Niels"},
{"nothing", nullptr},
{"answer", {
{"everything", 42}
}},
{"list", {1, 0, 2}},
{"object", {
{"currency", "USD"},
{"value", 42.99}
}}
};

serialization

// create object from string literal
json j = "{ \"happy\": true, \"pi\": 3.141 }"_json; // or even nicer with a raw string literal
auto j2 = R"(
{
"happy": true,
"pi": 3.141
}
)"_json; // parse explicitly
auto j3 = json::parse("{ \"happy\": true, \"pi\": 3.141 }"); // explicit conversion to string
std::string s = j.dump(); // {\"happy\":true,\"pi\":3.141} // serialization with pretty printing
// pass in the amount of spaces to indent
std::cout << j.dump(4) << std::endl;
// {
// "happy": true,
// "pi": 3.141
// }

read from file/save to file

// read a JSON file
std::ifstream i("file.json");
json j;
i >> j; // write prettified JSON to another file
std::ofstream o("pretty.json");
o << std::setw(4) << j << std::endl;

Arbitrary types conversions

namespace ns {
// a simple struct to model a person
struct person {
std::string name;
std::string address;
int age;
};
}

normal method

ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60};

// convert to JSON: copy each value into the JSON object
json j;
j["name"] = p.name;
j["address"] = p.address;
j["age"] = p.age; // ... // convert from JSON: copy each value from the JSON object
ns::person p {
j["name"].get<std::string>(),
j["address"].get<std::string>(),
j["age"].get<int>()
};

better method

using nlohmann::json;

namespace ns {
void to_json(json& j, const person& p) {
j = json{{"name", p.name}, {"address", p.address}, {"age", p.age}};
} void from_json(const json& j, person& p) {
j.at("name").get_to(p.name);
j.at("address").get_to(p.address);
j.at("age").get_to(p.age);
}
} // namespace ns // create a person
ns::person p {"Ned Flanders", "744 Evergreen Terrace", 60}; // conversion: person -> json
json j = p; std::cout << j << std::endl;
// {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"} // conversion: json -> person
auto p2 = j.get<ns::person>(); // that's it
assert(p == p2);

That's all! When calling the json constructor with your type, your custom to_json method will be automatically called. Likewise, when calling get<your_type>() or get_to(your_type&), the from_json method will be called.

How do I convert third-party types?

namespace nlohmann {

template <typename T>
struct adl_serializer {
static void to_json(json& j, const T& value) {
// calls the "to_json" method in T's namespace
} static void from_json(const json& j, T& value) {
// same thing, but with the "from_json" method
}
}; }

How can I use get() for non-default constructible/non-copyable types?

struct move_only_type {
move_only_type() = delete;
move_only_type(int ii): i(ii) {}
move_only_type(const move_only_type&) = delete;
move_only_type(move_only_type&&) = default; int i;
}; namespace nlohmann {
template <>
struct adl_serializer<move_only_type> {
// note: the return type is no longer 'void', and the method only takes
// one argument
static move_only_type from_json(const json& j) {
return {j.get<int>()};
} // Here's the catch! You must provide a to_json method! Otherwise you
// will not be able to convert move_only_type to json, since you fully
// specialized adl_serializer on that type
static void to_json(json& j, move_only_type t) {
j = t.i;
}
};
}

examples

#pragma once

#include <nlohmann/json.hpp>
using json = nlohmann::json;
#include "sensor_data.h"
#include "rfid_info.h" namespace nlohmann {
template <>
struct adl_serializer<SensorData> {
// note: the return type is no longer 'void', and the method only takes
// one argument
static SensorData from_json(const json& j) {
SensorData sensor_data;
sensor_data.sensor_identify = j.at("SensorIdentify").get<string>();
return sensor_data;
} // Here's the catch! You must provide a to_json method! Otherwise you
// will not be able to convert move_only_type to json, since you fully
// specialized adl_serializer on that type
static void to_json(json& j, SensorData t) {
j = json{ {"SensorIdentify",t.sensor_identify},{"SensorType",t.sensor_type },{"Data",t.data} };
}
};
template <>
struct adl_serializer<RfidInfo> {
// note: the return type is no longer 'void', and the method only takes
// one argument
static RfidInfo from_json(const json& j) {
RfidInfo rfid_info;
rfid_info.identify = j.at("Identify").get<string>();
return rfid_info;
} // Here's the catch! You must provide a to_json method! Otherwise you
// will not be able to convert move_only_type to json, since you fully
// specialized adl_serializer on that type
static void to_json(json& j, RfidInfo t) {
j = json{ { "Identify",t.identify },{ "Position",0 } };
}
};
}

Binary formats(BSON...)

// create a JSON value
json j = R"({"compact": true, "schema": 0})"_json; // serialize to BSON
std::vector<std::uint8_t> v_bson = json::to_bson(j); // 0x1B, 0x00, 0x00, 0x00, 0x08, 0x63, 0x6F, ... // roundtrip
json j_from_bson = json::from_bson(v_bson);

Reference

History

  • 20191012: created.

Copyright

nlohmann 最优秀的C++序列化工具库 详细入门教程的更多相关文章

  1. Python 数据处理库 pandas 入门教程

    Python 数据处理库 pandas 入门教程2018/04/17 · 工具与框架 · Pandas, Python 原文出处: 强波的技术博客 pandas是一个Python语言的软件包,在我们使 ...

  2. 程序员用于机器学习编程的Python 数据处理库 pandas 入门教程

    入门介绍 pandas适合于许多不同类型的数据,包括: · 具有异构类型列的表格数据,例如SQL表格或Excel数据 · 有序和无序(不一定是固定频率)时间序列数据. · 具有行列标签的任意矩阵数据( ...

  3. 【荐】PHP采集工具curl快速入门教程

    为什么要用CURL? CURL(Client URL Library Functions)是一个利用URL语法在命令行方式下工作的文件传输工具.它支持很多协议:FTP, FTPS, HTTP, HTT ...

  4. 信息收集工具recon-ng详细使用教程

    前言: 最近在找Recon-ng详细一点的教程,可是Google才发现资料都很零散而且不详细,所以我打算具体写一下.Recon-ng在渗透过程中主要扮演信息收集工作的角色,同时也可以当作渗透工具,不过 ...

  5. [C++]Linux之图形界面编程库[curses库]之入门教程

    1. 安装 //方法一 sudo apt-get install libncurses5-dev [ ubuntu 16.04:亲测有效] //方法二 sudo apt-get install ncu ...

  6. 自动化测试工具 Test Studio入门教程

    Test Studio安装 可以到下载试用版 官网 http://www.telerik.com/teststudio , 装完以后需要装silverlight 安装好了,主界面是介个样子的 Test ...

  7. Modbus 仿真测试工具 Mod_Rssim 详细图文教程

    Mod_RSsim是一款轻量级的Modbus从机模拟器,它可以模拟ModBusTCP和ModBusRTU的从机,能够同时模拟254个被控站,软件使用简单方便,可以满足一般的主机调试. 官方网站:www ...

  8. Google FlatBuffers——开源、跨平台的新一代序列化工具

    前段时间刚试用了一个序列化工具cereal,请看cereal:C++实现的开源序列化库,打算再总结下我对google proto buf序列化库的使用呢, 结果还没动手,大Google又出了一个新的. ...

  9. Lo-Dash – 替代 Underscore 的优秀 JS 工具库

    前端开发人员大都喜欢 Underscore,它的工具函数很实用,用法简单.这里给大家推荐另外一个功能更全面的 JavaScript 工具——Lo-Dash,帮助你更好的开发网站和 Web 应用程序. ...

随机推荐

  1. 一篇文章带你解读Redis分布式锁的发展史和正确实现方式

    前言 近两年来微服务变得越来越热门,越来越多的应用部署在分布式环境中,在分布式环境中,数据一致性是一直以来需要关注并且去解决的问题,分布式锁也就成为了一种广泛使用的技术,常用的分布式实现方式为Redi ...

  2. VS Code 成主宰、Vue 备受热捧!2019 前端开发趋势必读

    前端在生产和开发中占据着越来越重要的地位,PC 端.手机端.桌面端.智能手表端等等设备都离不开前端的身影.本文将围绕框架.编程语言.工具.React.Vue 等方面,全面回顾 2019 年前端与 We ...

  3. linux目录的读(r)、写(w)、执行(x)权限说明

    linux目录的读.写.执行权限说明 1.可读r #表示具有浏览目录下面文件及子目录的权限.即ls dir 1)如果没有x权限,不能进到目录里,即无法 cd dir 2)如果没有x权限,ls列表可以看 ...

  4. 中国剩余定理(CRT)及其拓展(ExCRT)

    中国剩余定理 CRT 推导 给定\(n\)个同余方程 \[ \left\{ \begin{aligned} x &\equiv a_1 \pmod{m_1} \\ x &\equiv ...

  5. 《Java基础知识》Java包装类,拆箱和装箱

    虽然 Java 语言是典型的面向对象编程语言,但其中的八种基本数据类型并不支持面向对象编程,基本类型的数据不具备“对象”的特性——不携带属性.没有方法可调用. 沿用它们只是为了迎合人类根深蒂固的习惯, ...

  6. 《Dotnet9》系列-Google ProtoBuf在C#中的简单应用

    时间如流水,只能流去不流回! 点赞再看,养成习惯,这是您给我创作的动力! 本文 Dotnet9 https://dotnet9.com 已收录,站长乐于分享dotnet相关技术,比如Winform.W ...

  7. tune kubernetes eviction parameter

    Highlight 本文会介绍kubernetes中关于集群驱逐的相关参数, 合理设置驱逐速率的考虑因素, 但是不会涉及node层面资源的驱逐阈值的设置. Basic 在kubernetes中, 如果 ...

  8. SpringCloud服务降级案列

    一.什么是服务降级 所有的RPC技术里面服务降级是一个最为重要的话题,所谓的降级指的是当服务的提供方不可使用的时候,程序不会出现异常,而会出现本地的操作 二.服务降级案例 1.目录展示 2.导入依赖 ...

  9. Spring基础——IOC九种bean声明方式

    Spring简介 Spring不是服务于开发web项目的功能,或业务.而是服务于项目的开发,方便各层间的解耦调用,方便对类的批量管理,是提高软件开发效率,降低后期维护成本的框架. Spring的核心思 ...

  10. flask项目部署到生产环境的方案

    背景 使用Python+flask编写的一个小项目,在本地开发完毕后,需要部署到测试服务器上,这时候犯难了,因为之前没部署过这块东西,所以各种百度,总算是部署成功了,也对这个项目进行了jenkins持 ...