C++ 对数据包进行 JSON 解析
时间: 2024-03-20 07:41:39 浏览: 17
在 C++ 中进行 JSON 解析可以使用第三方库,例如 RapidJSON。
以下是一个基本的示例代码:
```c++
#include <iostream>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
int main() {
// JSON 数据字符串
const char* json = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
// 解析 JSON 数据
Document doc;
doc.Parse(json);
// 获取解析后的数据
std::string name = doc["name"].GetString();
int age = doc["age"].GetInt();
std::string city = doc["city"].GetString();
// 输出解析后的数据
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "City: " << city << std::endl;
return 0;
}
```
输出结果为:
```
Name: John
Age: 30
City: New York
```
当然,这只是一个简单的示例,实际应用中需要根据具体需求进行更复杂的 JSON 解析。