json for modern c++是一个德国大牛nlohmann写的.

地址 https://github.com/nlohmann/json 

只有一个头文件 json.hpp

使用时,直接#include "json.hpp"

再using namespace nlohmann; 

就可以用了。比腾讯的什么垃圾RapidJSON好了不知道一百倍。

解析字符串的方法是:

1. 在字符串末尾添加 _json

using namespace nlohmann;

auto j2 = R"({"happy": true, "pi": 3.141, "ren":"good"})"_json;

 

2.明确解析

string jsonStr = R"({"happy": true, "pi": 3.141, "ren":"good"})";
	
//第2个参数是错误处理,第3个参数是不throw exception
nlohmann::json j3 = json::parse(jsonStr, nullptr, false);

if (j3.is_discarded())
{
	printf("json::parse error!\n");
	return -1;
}

获取值的方法

 

if (j3["ren"].is_string())
	string renStr = j3["ren"];


bool happy = j3["happy"].get<bool>();

用is_string()来进行判断,避免此key为空的情况,会报异常导致程序挂掉。

同样还有 is_number_integer()   is_array() 等等

 

生成json字符串

	nlohmann::json j3;
	j3["hash"] = "abcdefg";
	j3["from"] = 0;
	j3["to"]   = 10;
	
	auto jarray = nlohmann::json::array();
	jarray.emplace_back(j3);
	auto str = jarray.dump();

 

 

更多使用方法请参考:

https://blog.csdn.net/fengxinlinux/article/details/71037244

https://blog.csdn.net/forrid/article/details/78867679

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐