jsoncpp构建json嵌套
时间: 2023-10-11 14:08:40 浏览: 207
jsoncpp 库
4星 · 用户满意度95%
你可以使用JsonCpp库来构建嵌套的JSON对象。下面是一个示例代码:
```cpp
#include <iostream>
#include "json/json.h"
int main() {
// 创建JSON对象
Json::Value root;
// 添加简单类型数据
root["name"] = "John";
root["age"] = 30;
// 添加嵌套JSON对象
Json::Value address;
address["street"] = "Main Street";
address["city"] = "New York";
address["state"] = "NY";
address["zip"] = "10001";
root["address"] = address;
// 添加嵌套JSON数组
Json::Value hobbies(Json::arrayValue);
hobbies.append("reading");
hobbies.append("traveling");
hobbies.append("photography");
root["hobbies"] = hobbies;
// 将JSON对象转换为字符串
std::string json_str = root.toStyledString();
std::cout << json_str << std::endl;
return 0;
}
```
输出结果如下:
```json
{
"name" : "John",
"age" : 30,
"address" : {
"street" : "Main Street",
"city" : "New York",
"state" : "NY",
"zip" : "10001"
},
"hobbies" : [
"reading",
"traveling",
"photography"
]
}
```
阅读全文