nlohmann::json 怎么解析 "code":0,"msg":"ok","err_code":10000,"result":{"deviceSecret":"3d3f96f62e258669ab5f5c0ba54d97970","productKey":"test","deviceName":"MPC6K7PhdTwEF66Tmiv82","productSecret":"xxx3"}}
时间: 2023-07-03 21:22:48 浏览: 72
你可以使用 nlohmann::json 库的 parse() 方法将这段 JSON 字符串解析成一个 json 对象,然后通过访问 json 对象的成员来获取对应的属性值。示例如下:
```
#include <nlohmann/json.hpp>
using json = nlohmann::json;
std::string jsonStr = "{\"code\":0,\"msg\":\"ok\",\"err_code\":10000,\"result\":{\"deviceSecret\":\"3d3f96f62e258669ab5f5c0ba54d97970\",\"productKey\":\"test\",\"deviceName\":\"MPC6K7PhdTwEF66Tmiv82\",\"productSecret\":\"xxx3\"}}";
json j = json::parse(jsonStr);
int code = j["code"];
std::string msg = j["msg"];
int err_code = j["err_code"];
std::string deviceSecret = j["result"]["deviceSecret"];
std::string productKey = j["result"]["productKey"];
std::string deviceName = j["result"]["deviceName"];
std::string productSecret = j["result"]["productSecret"];
```
这里我们首先定义了一个包含 JSON 字符串的 std::string 对象 jsonStr,然后使用 json::parse() 方法将其解析成一个 json 对象 j。接着,我们通过访问 json 对象的成员来获取对应的属性值,最终将它们存储到相应的变量中。需要注意的是,json 对象的成员可以通过下标运算符 [] 或成员函数 at() 来访问,但是如果成员不存在,使用下标运算符会返回一个默认值,而使用 at() 方法会抛出异常。因此,在访问 json 对象的成员时,需要根据情况选择合适的方法来保证代码的健壮性。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)