jsoncpp用法
时间: 2023-07-29 18:13:32 浏览: 100
JsonCpp是一个用于处理JSON数据的C++库。以下是使用JsonCpp的一些常见用法:
1. 解析JSON字符串
```cpp
#include <json/json.h>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream ifs("data.json");
Json::Value root;
Json::CharReaderBuilder readerBuilder;
JSONCPP_STRING errs;
if (!Json::parseFromStream(readerBuilder, ifs, &root, &errs)) {
std::cout << errs << std::endl;
return 1;
}
// use root to access json data
std::string name = root["name"].asString();
int age = root["age"].asInt();
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
return 0;
}
```
2. 生成JSON字符串
```cpp
#include <json/json.h>
#include <iostream>
int main()
{
Json::Value root;
root["name"] = "John";
root["age"] = 30;
Json::FastWriter writer;
std::string json_str = writer.write(root);
std::cout << json_str << std::endl;
return 0;
}
```
3. 遍历JSON对象
```cpp
#include <json/json.h>
#include <iostream>
void printJson(Json::Value &root, int depth = 0)
{
if (root.isObject()) {
std::cout << std::string(depth, ' ') << "{" << std::endl;
for (auto it = root.begin(); it != root.end(); ++it) {
std::cout << std::string(depth + 4, ' ') << it.name() << ": ";
printJson(*it, depth + 4);
}
std::cout << std::string(depth, ' ') << "}" << std::endl;
} else if (root.isArray()) {
std::cout << std::string(depth, ' ') << "[" << std::endl;
for (auto it = root.begin(); it != root.end(); ++it) {
printJson(*it, depth + 4);
}
std::cout << std::string(depth, ' ') << "]" << std::endl;
} else {
std::cout << root.asString() << std::endl;
}
}
int main()
{
std::string json_str = "{\"name\":\"John\",\"age\":30,\"hobbies\":[\"reading\",\"swimming\"]}";
Json::Value root;
Json::CharReaderBuilder readerBuilder;
JSONCPP_STRING errs;
if (!Json::parseFromStream(readerBuilder, json_str, &root, &errs)) {
std::cout << errs << std::endl;
return 1;
}
printJson(root);
return 0;
}
```
以上是JsonCpp的一些基本用法,更多用法可以参考JsonCpp的文档。
阅读全文