nlohmann::json 解析以下json字段的完整代码 "code":0,"msg":"ok","err_code":10000,"result":{"deviceSecret":"3d3f96f62e258669ab5f5c0ba54d97970","productKey":"test","deviceName":"MPC6K7PhdTwEF66Tmiv82","productSecret":"xxx3"}}
时间: 2023-07-05 12:21:18 浏览: 88
完整代码示例如下:
```
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main() {
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"];
std::cout << "code: " << code << std::endl;
std::cout << "msg: " << msg << std::endl;
std::cout << "err_code: " << err_code << std::endl;
std::cout << "deviceSecret: " << deviceSecret << std::endl;
std::cout << "productKey: " << productKey << std::endl;
std::cout << "deviceName: " << deviceName << std::endl;
std::cout << "productSecret: " << productSecret << std::endl;
return 0;
}
```
这里我们首先定义了一个包含 JSON 字符串的 std::string 对象 jsonStr,然后使用 json::parse() 方法将其解析成一个 json 对象 j。接着,我们通过访问 json 对象的成员来获取对应的属性值,最终将它们存储到相应的变量中。最后,我们使用 std::cout 输出这些变量的值。
阅读全文