qmqtt订阅得数据为json数据,解析json数据
时间: 2024-02-26 09:57:56 浏览: 56
要解析json格式的数据,可以使用json库。在C++中,常用的json库有RapidJSON、nlohmann/json等。
以RapidJSON为例,假设我们有一个json格式的字符串:
```json
{
"name": "Alice",
"age": 25,
"hobbies": ["reading", "swimming", "traveling"],
"address": {
"city": "Beijing",
"country": "China"
}
}
```
我们可以通过以下代码解析这个json字符串:
```c++
#include <iostream>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
int main() {
const char* json = "{\"name\":\"Alice\",\"age\":25,\"hobbies\":[\"reading\",\"swimming\",\"traveling\"],\"address\":{\"city\":\"Beijing\",\"country\":\"China\"}}";
Document document;
document.Parse(json);
std::string name = document["name"].GetString();
int age = document["age"].GetInt();
const Value& hobbies = document["hobbies"];
assert(hobbies.IsArray());
for (SizeType i = 0; i < hobbies.Size(); i++) {
std::string hobby = hobbies[i].GetString();
std::cout << hobby << std::endl;
}
const Value& address = document["address"];
assert(address.IsObject());
std::string city = address["city"].GetString();
std::string country = address["country"].GetString();
std::cout << city << ", " << country << std::endl;
return 0;
}
```
解析后输出的结果为:
```
reading
swimming
traveling
Beijing, China
```
可以看到,我们可以通过Document对象的成员函数来解析json数据。其中,Parse函数用于解析json字符串,[]操作符用于获取json对象中的某个值,GetString函数用于获取字符串类型的值,GetInt函数用于获取整型值,IsArray和IsObject函数用于判断值的类型。
阅读全文