c++中写一个函数传入的json value格式转换成map格式
以下是一个将 JSON value 格式转换为 map 格式的示例代码:
#include <iostream>
#include <map>
#include "json/json.h"
std::map<std::string, std::string> jsonValueToMap(const Json::Value& jsonValue) {
std::map<std::string, std::string> resultMap;
if (jsonValue.isObject()) {
const auto& members = jsonValue.getMemberNames();
for (const auto& member : members) {
const auto& value = jsonValue[member];
if (value.isString()) {
resultMap[member] = value.asString();
}
}
}
return resultMap;
}
int main() {
std::string jsonString = R"({
"name": "Alice",
"age": 25
})";
Json::Value jsonValue;
Json::Reader reader;
if (reader.parse(jsonString, jsonValue)) {
auto resultMap = jsonValueToMap(jsonValue);
for (const auto& pair : resultMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
}
return 0;
}
该示例代码使用了第三方库 jsoncpp 来处理 JSON 格式的数据。在该示例中,我们定义了一个 jsonValueToMap 函数,该函数接受一个 Json::Value 对象作为参数,并将其转换为 std::map<std::string, std::string> 格式的数据,最后返回这个 std::map 对象。
在函数中,我们首先判断了这个 Json::Value 对象是否是一个 JSON 对象(jsonValue.isObject())。如果是,我们遍历了这个对象中的每一个成员,并将其转换为一个 std::pair<std::string, std::string> 对象,然后将这个对象添加到结果 std::map 中。
在 main 函数中,我们首先定义了一个 JSON 格式的字符串,然后使用 Json::Reader 对象将其解析为一个 Json::Value 对象。接着,我们调用了 jsonValueToMap 函数,并将解析得到的 Json::Value 对象作为参数传递给它。最后,我们遍历了转换后的 std::map 对象,并将其内容打印到屏幕上。
需要注意的是,该示例代码只处理了 JSON 对象中的字符串类型的成员。如果需要处理其他类型的数据,需要对函数进行相应的修改。
原文地址: https://www.cveoy.top/t/topic/bIg8 著作权归作者所有。请勿转载和采集!