前言

最近在搞一个C++项目,用到了json和类的相互转化。但是c++没有反射,也没有像java一个方便的插件,没法办只能自己搞一个了。网上找了一下,发现nlohmann::json不错。已经运用到实际项目代码中,这里记录下。

下载源码

源码下载

解压之后,只需要包含 single_include\nlohmann\json.hpp 文件即可

示例

编译时,需要编译器支持c++11。linux中,g++ -std=c++11 ,windows中使用支持c++11的编译器

#include <iostream>
#include "D:\\single_include\\nlohmann\\json.hpp"using json = nlohmann::json;
using namespace std;namespace nlohmann {class videoinfo {public:int id;string name;};//json转class用到,需要自定义//This function is usually called by the get() function of the basic_json class (either explicitly or via the conversion operators).void from_json(const json& j, videoinfo& v) {j.at("id").get_to(v.id);j.at("name").get_to(v.name);}//class转json用到,需要自定义//This function is usually called by the constructors of the basic_json class.void to_json(json& j, const videoinfo& value){j = json{ {"id", value.id}, {"name",value.name} };}
};int main()
{json j = { {"id",3},{"name","jiahui"}};//json转classauto x = m.get<nlohmann::videoinfo>();//class转jsonjson m = x;//获取字符串string str = j.dump();std::cout << "Hello World!\n";
}

以上只演示了string和class之间的转换,如果需要其他的操作
参考这里:
官网:https://nlohmann.github.io/json/api/basic_json/
中文:https://www.cnblogs.com/linuxAndMcu/p/14503341.html#_label2_5
https://www.cnblogs.com/kezunlin/p/12058300.html

遇到的问题

1.如果字符串(json object)初始化json对象,没有得到json的object类型,依然是string。解决方法是初始化时使用迭代器。
比如:

std::string s = "{\"happy\":true,\"pi\":3.141}";
json m = json::parse(s.begin(), s.end());

2.如果定义的类中没有默认构造函数,那么你需要这样实现转换函数(上面的例子有默认构造函数)

namespace nlohmann
{
template <>
struct adl_serializer<nlohmann::videoinfo>
{static nlohmann::videoinfo from_json(const json& j){return {j.at("id"), j.at("name")};}static void to_json(json& j, nlohmann::videoinfo p){j["name"] = p.name;j["id"] = p.id;}
};
}

3.当调用json.at()方法时注意,这个方法会抛出异常,需要处理。

4.类继承中如何使用json

class A {
public:A() : A_name("aaa"), A_age(10) {}virtual ~A(){}friend void to_json(nlohmann::json& j, const A e);friend void from_json(const nlohmann::json& j, A& e);protected://这里的属性权限为protected,应为需要子类给赋值string A_name;int    A_age;
};void to_json(nlohmann::json& j, const A e)
{j = nlohmann::json{{"A_name", e.A_name},{"A_age", e.A_age}};
}void from_json(const nlohmann::json& j, A& e)
{j.at("A_name").get_to(e.A_name);j.at("A_age").get_to(e.A_age);
}class B : public A
{
public:B() :B_address("b_address") {}virtual ~B() {}friend void to_json(nlohmann::json& j, const B& e);friend void from_json(const nlohmann::json& j, B& e);
private:string B_address;
};void to_json(nlohmann::json& j, const B& e)
{j = static_cast<A>(e);j["B_address"] = e.B_address;
}void from_json(const nlohmann::json& j, B& e)
{  from_json(j, static_cast<A&>(e));j.at("B_address").get_to(e.B_address);
}int main()
{string str = "{\"A_age\":3333,\"A_name\":\"1111\",\"B_address\":\"xxxx\"}";nlohmann::json dataJ = nlohmann::json::parse(str);B x;from_json(dataJ, x);B b;nlohmann::json j = b;cout << j.dump() << endl;
}

5.编码问题
本库只支持utf-8编码格式,其他格式会报异常。

怎么处理编码转换,参考这里

6.如果你的数据结构很复杂,建议参考使用这个扩展,反射功能,无需再手动写from_jsonto_json

7.如果你的类字段为基础类型,那么可以使用库提供的注册宏,不需要自定义两个序列化函数。

NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(name, member1, member2, …) 将在要为其创建代码的类/结构的命名空间内定义。
NLOHMANN_DEFINE_TYPE_INTRUSIVE(name, member1, member2, …) 将在要为其创建代码的类/结构中定义。 该宏还可以访问私有成员。

举例:

class A {
public:A() : A_name("aaa"), A_age(10) {}virtual ~A(){}NLOHMANN_DEFINE_TYPE_INTRUSIVE(A, A_name, A_age);
protected://这里的属性权限为protected,应为需要子类给赋值string A_name;int    A_age;
};

C++ 之 nlohmann::json 一个不错的json库相关推荐

  1. 一个不错的机器视觉库 SimpleCV: a kinder, gentler machine vision library

    Computer Vision platform using Python. WHAT IS IT? SimpleCV is an open source framework for building ...

  2. 自己动手实现一个简单的JSON解析器

    1. 背景 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.相对于另一种数据交换格式 XML,JSON 有着诸多优点.比如易读性更好,占用空间更少等.在 ...

  3. SpringBoot中怎样对外开放一个接口返回Json数据

    场景 在SpringBoot中开放一个接口,使C#程序中能访问接口并接受返回的数据. 实现 封装一个Json类 import lombok.Data;import java.io.Serializab ...

  4. json string 格式_自己动手实现一个简单的JSON解析器

    作者:田小波 原文:http://cnblogs.com/nullllun/p/8358146.html 1. 背景 JSON(JavaScript Object Notation) 是一种轻量级的数 ...

  5. 服务器返回一个无效的JSON string,处理

    使用AFN,服务端返回的结果看看哪里错了. 因为后台返回的不是一个有效的JSON string 所以库里面转化的时候一个error就抛出了.所以这时候,就自己做解析好了. NSLog ( @" ...

  6. 一个简单的json解析器

    实现一个简单地json解析器. 两部分组成,词法分析.语法分析 词法分析 package com.mahuan.json;import java.util.LinkedList; import jav ...

  7. 饿了么商家开放平台踩坑记录2,php更新商品信息提示attribute:[]不是一个有效的JSON对象 By勤勤学长 Qq318692996

    需要注意的是,这个attribute:[]不是一个有效的JSON对象的错误提示,并不是attributes这个参数出错. 经过我一天的排查,终于发现问题所在,是你其中一个参数不正确. 我这里报错是设置 ...

  8. excel2json 一个excel转json的工具(开源)

    excel2json 一个excel转json的工具 开源地址:https://github.com/zdhsoft/excel2json 这个工具是基于python 2.7.x(已经增加了3.x的版 ...

  9. 手写了一个简单的JSON解析器,网友直乎:牛!

    作者 | 田小波 来源 | http://r3m2u.cn/4455O 背景 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.相对于另一种数据交换格式 X ...

最新文章

  1. windows10+Python3.7安装dlib库进行面部标志识别
  2. jquery的$().each,$.each的区别
  3. Opencv 图片融合 addWeighted性能测试
  4. queueing 优化_网站加载性能
  5. 定制属于自己的域名邮箱
  6. boost::program_options::options_description相关的测试程序
  7. OpenGL阴影贴图
  8. java printstacktrace_为什么异常. printStackTrace() 被认为是不好的实践?_java_酷徒编程知识库...
  9. yii2中的rules 自定义验证规则详解
  10. 产品经理基本功:消息推送设计
  11. Python实现图像信息隐藏
  12. Linux面试必备20个常用命令
  13. 智慧档案库房库房一体化安全管控平台方案【转载】
  14. Mac安装telnet工具和使用
  15. 黄色一般表示碳膜电阻,蓝色金属膜,灰色保险电阻
  16. python特征相关性热力图怎么画_百度热力图,带您探索城市的奥妙!
  17. 7.27 web前端-淘宝首页设计3
  18. vue实现微信扫码拨打电话
  19. stata学习笔记|异方差问题
  20. JS逆向:猿人学爬虫比赛第九题详细题解

热门文章

  1. A. AD 2020
  2. Qt5.6 编译后在 xp 系统下运行
  3. python argsparse_如何创建Python命名空间(argparse.parse_args值)?
  4. android 图片转换圆形 黑色背景,Android 更改纯色背景图片颜色,可实现一张背景圆形图片展示不同颜色...
  5. Jmeter 正则表达式提取器——身份证切取
  6. 短网址生成php源码
  7. 2020年ECCV论文DeepSFM: Structure From Motion Via Deep Bundle Adjustment阅读笔记
  8. Unity 之 DontDestroyOnLoad的使用
  9. ACADOS学习(1)
  10. C语言三大标准C89,C99和C11