[jsoncpp]JSON序列化与反序列化
JSONCpp是一个C++库,用于剖析和生成JSON数据。在本文中,我们将先容JSONCpp的基本用法,包括怎样剖析JSON数据、怎样访问JSON对象和数组,以及怎样生成JSON数据。1. 下载和编译JSONCpp
首先,确保您已经安装了JSONCpp库:
git clone --depth 1 https://ghproxy.cn/https://github.com/open-source-parsers/jsoncpp.git
cd jsoncpp/
mkdir build
cd build/
cmake ..
make
2. 剖析JSON数据
要剖析JSON数据,您必要创建一个Json::Value对象来存储剖析后的JSON数据。然后,使用Json::CharReaderBuilder和Json::parseFromStream函数从字符串中剖析JSON数据。以下是一个示例:
#include <iostream>
#include <sstream>
#include <json/json.h>
int main() {
Json::Value root;
Json::CharReaderBuilder builder;
std::string errors;
// 使用非const字符串
std::string json_data = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
std::istringstream json_stream(json_data);
bool parsingSuccessful = Json::parseFromStream(builder, json_stream, &root, &errors);
if (parsingSuccessful) {
std::cout << "Name: " << root["name"].asString() << std::endl;
std::cout << "Age: " << root["age"].asInt() << std::endl;
std::cout << "City: " << root["city"].asString() << std::endl;
} else {
std::cout << "Failed to parse JSON: " << errors << std::endl;
}
return 0;
}
3. 访问JSON对象和数组
剖析乐成后,您可以通过Json::Value对象访问JSON数据。以下是一个示例,演示怎样访问JSON对象和数组:
#include <iostream>
#include <sstream>
#include <json/json.h>
int main() {
Json::Value root;
Json::CharReaderBuilder builder;
std::string errors;
const std::string json_data = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\", \"hobbies\":[\"reading\", \"traveling\"]}";
std::istringstream json_stream(json_data);
bool parsingSuccessful = Json::parseFromStream(builder, json_stream, &root, &errors);
if (parsingSuccessful) {
const Json::Value& hobbies = root["hobbies"];
for (unsigned int i = 0u; i < hobbies.size(); ++i) {
std::cout << "Hobby: " << hobbies.asString() << std::endl;
}
} else {
std::cout << "Failed to parse JSON: " << errors << std::endl;
}
return 0;
}
4. 生成JSON数据
要生成JSON数据,您必要创建一个Json::Value对象,然后使用其成员函数添加数据。以下是一个示例,演示怎样生成JSON数据:
#include <iostream>
#include <sstream>
#include <jsoncpp/json/json.h>
int main() {
Json::Value root;
root["name"] = "John";
root["age"] = 30;
root["city"] = "New York";
Json::Value hobbies;
hobbies.append("reading");
hobbies.append("traveling");
root["hobbies"] = hobbies;
std::cout << "Generated JSON: " << root.toStyledString() << std::endl;
return 0;
}
编译程序
g++ --std=c++11 -o gen gen.cpp-I../include -L./lib -ljsoncpp
执行程序得到:
Generated JSON: {
"age" : 30,
"city" : "New York",
"hobbies" :
[
"reading",
"traveling"
],
"name" : "John"
}
在这个示例中,我们创建了一个Json::Value对象,然后使用其成员函数添加JSON数据。末了,我们使用toStyledString()函数将生成的JSON数据转换为字符串并输出。
总结
JSONCpp是一个功能强盛的C++库,用于剖析和生成JSON数据。通过本文,我们先容了JSONCpp的基本用法,包括怎样剖析JSON数据、怎样访问JSON对象和数组,以及怎样生成JSON数据。您可以根据必要查阅JSONCpp的官方文档以获取更多信息。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]