用c plus plus 14 写一个函数解析json消息成结构体,json消息已经被存在Json::Value类型变量json信息是这个样子“{ "devTimeScheduleItemList": [{ "event": 1, // 执行事件(1:自动清扫) "time": "11:11:11" // 执行调度时间 }, { "event": 1, "time": "04:04:04" }, { "event": 1, "time": "05:05:04" }]}”
时间: 2023-06-05 18:07:28 浏览: 145
这是一个技术问题,我可以回答。下面是一个用 C++14 解析 JSON 消息成结构体的示例代码:
```c++
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <memory>
#include <chrono>
#include <thread>
#include <ctime>
#include <iomanip>
#include <json/json.h>
using namespace std;
struct TimeEvent {
int event;
string time;
};
struct DevTimeScheduleItemList {
vector<TimeEvent> itemList;
};
DevTimeScheduleItemList parseJsonToStruct(Json::Value json) {
DevTimeScheduleItemList result;
for (auto item : json["devTimeScheduleItemList"]) {
TimeEvent timeEvent;
timeEvent.event = item["event"].asInt();
timeEvent.time = item["time"].asString();
result.itemList.push_back(timeEvent);
}
return result;
}
int main() {
// 假设 jsonMessage 是从网络或文件读取的 JSON 消息
string jsonMessage = "{ \"devTimeScheduleItemList\": [{ \"event\": 1, \"time\": \"11:11:11\" }, { \"event\": 1, \"time\": \"04:04:04\" }, { \"event\": 1, \"time\": \"05:05:04\" }] }";
Json::Value json;
Json::CharReaderBuilder builder;
auto reader = unique_ptr<Json::CharReader>(builder.newCharReader());
string errors;
bool parsingSuccessful = reader->parse(jsonMessage.c_str(), jsonMessage.c_str() + jsonMessage.size(), &json, &errors);
if (!parsingSuccessful) {
cout << "Failed to parse JSON: " << errors << endl;
return 1;
}
DevTimeScheduleItemList scheduleItemList = parseJsonToStruct(json);
// 输出解析结果
for (auto item : scheduleItemList.itemList) {
cout << "event: " << item.event << ", time: " << item.time << endl;
}
return 0;
}
```
阅读全文