C++:nlohmann::json 使用

一、nlohmann::json介绍

 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;
	}



二、实际应用(MQTT报文负载部分使用json序列化)

    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<ConfigInfo>(cmd.get_val());
    nlohmann::json js;
    js["version"] = 2;
    std::map<std::string, std::string> 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<ConfigInfo>(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<std::string, std::string> 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<ConfigInfo>(cmd.get_val());
    nlohmann::json js;
    js["version"] = 2;

    std::vector<nlohmann::json> data_report;
    data_report.reserve(info.yc_num_set+info.yx_num_set);
    for(size_t i = 0; i <info.yc_num_set ; i++){
        nlohmann::json js_item;
        js_item["tagname"] = info.tag_name_set[i];
        js_item["quality"] = 0;
        js_item["value"] = info.yc_sig_set[i];
        js_item["time"] = get_sys_time();

        data_report.push_back(js_item);
    }
    for(size_t i = info.yc_num_set; i < (info.yc_num_set+info.yx_num_set); i++){
        nlohmann::json js_item;
        js_item["tagname"] = info.tag_name_set[i];
        js_item["quality"] = 0;
        js_item["value"] = info.yx_sig_set[i];
        js_item["time"] = get_sys_time();

        data_report.push_back(js_item);
    }

    js["message"]["data"] = data_report;

    std::string msg = js.dump();
    for (auto it = msg.begin(); it != msg.end(); it++) {
        uint8_t ch = *it;
        tmp.push_back(ch);
    }

  • 7
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值