nlohmann::json需要使用到头文件:#include "json.hpp"
1、创建json对象
json js;
js["name"]="joe";//字符串
js["number"]=12;//整数
js["status"]=true;//布尔值
js["food"]={"ice cream","beef","apple"};//数组
js["message"]["data"]="111";//对象中元素值
js["message"]={{"id","fff"},{"ip","192.168.1.1"}};//对象
2、序列化和反序列化
dump()函数:用于序列化,其返回值为string,格式是JSON文本形式。由于默认格式是紧凑输出,没有缩进,可以添加参数进行缩进,显得更容易阅读。
parse()函数:用来对string进行反序列化,直接得到JSON对象,可以使用auto自动推导类型。
//序列化
string str1 = j.dump();
string str2 = j.dump(2);
cout << str1 << endl; // 序列化,无缩进
cout << str2 << endl; // 序列化,有缩进,2个空格
//反序列化
// JSON文本,原始字符串,不要在R的行里面加注释,写了会被带到字符串里,导致parse异常
string str = R"({
"name": "joe",
"age" : 21,
"married" : true
})";
try
{
auto j = json_t::parse(str); // 从字符串反序列化
assert(j["age"] == 23); // 验证序列化是否正确
assert(j["name"] == "peter");
cout << j["age"] << endl;
cout << j["name"] << endl;
}
catch(std::exception& e) // 捕获异常
{
cout << "json反序列化失败" << endl;
cout << e.what() << endl;
}
1、 json的嵌套类型1:
{
"message" : {
"ads_ip" : "192.168.1.1",
"adsid" : "COT97",
"date_send" : "2022-10-24 14:25:21",
"productid" : "COT97",
"ssl" : "0"
},
"version" : 2
}
代码实现部分:
//消息处理和填充
auto info = boost::any_cast(cmd.get_val());
nlohmann::json js;
js["version"] = 2;
std::map m = {
{"adsid",info.gateway_id_set},
{"ssl","0"},
{"productid",info.gateway_id_set},
{"ads_ip",info.gateway_ip_set},
{"date_send",get_sys_time()}
};
js["message"] = m;
std::string msg = js.dump();
for (auto it = msg.begin(); it != msg.end(); it++) {
uint8_t ch = *it;
tmp.push_back(ch);
}
2、json的嵌套类型2:
{
"adsid" : "COT97",
"adstype" : "OPC",
"device" : [ {
"pwr" : "3334-0-1O-sxxp-000001",
"soc" : "3334-0-1O-sxxp-000002"
} ],
"productid" : "COT97",
"version" : 2
}
代码实现部分:
//消息处理和填充
auto info = boost::any_cast(cmd.get_val());
nlohmann::json js;
js["version"] = 2;
js["adstype"] = "OPC";
js["adsid"] = info.gateway_id_set;
js["productid"] = info.gateway_id_set;
std::map m;
for(int i = 0; i < (info.yc_num_set + info.yx_num_set); i++){
m.insert({info.pcs_name_set[i],info.tag_name_set[i]});
}
js["device"] = {m};
std::string msg = js.dump();
for (auto it = msg.begin(); it != msg.end(); it++) {
uint8_t ch = *it;
tmp.push_back(ch);
}
3、 json的嵌套类型3:
{
"message" : {
"data" : [ {
"quality" : 0,
"tagname" : "3334-0-1O-sxxp-000001",
"time" : "2022-10-24 14:10:30",
"value" : 2.0
}, {
"quality" : 0,
"tagname" : "3334-0-1O-sxxp-000002",
"time" : "2022-10-24 14:10:30",
"value" : 3.0
} ]
},
"version" : 2
}
代码实现部分:
//消息处理和填充
auto info = boost::any_cast(cmd.get_val());
nlohmann::json js;
js["version"] = 2;
std::vector data_report;
data_report.reserve(info.yc_num_set+info.yx_num_set);
for(size_t i = 0; i