新版Jsoncpp用法

在新的Jsoncpp中 Json::Writer、Json::FastWriter、Json::Reader 等都被摒弃了,

用了新的Json::StreamWriterBuilder、Json::CharReaderBuilder代替。

下面是示例用法:

1、把现有数据拼装成Json字符串

string strRes = "";
Json::Value root;
Json::StreamWriterBuilder jsrocd;
std::unique_ptr<Json::StreamWriter> write(jsrocd.newStreamWriter());
ostringstream os;

root["Name"] = "张三";
root["Age"] = 20;

write->write(root, &os);
strRes = os.str();

2、解析Json字符串(直接拿上面的strRes来用了。)

int nLen = strRes.length();

Json::Value root;
Json::CharReaderBuilder jsreader;
std::unique_ptr<Json::CharReader> const reader(jsreader.newCharReader());
const char *pStart = record.c_str();

string err;

//失败

if (!reader->parse(pStart, pStart + nLen, &root, &err))
return false;

string strName = root["Name"].asString();
int strAge = root["Age"].asInt();


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的文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值