JsonCpp解析和读写Json字符串
时间:2020年5月17日11:37:10
JsonCPP 改版了,以前的 Json::Reader, Json::Parse被弃用了,得用新的方法。
JsonCpp项目地址:https://github.com/open-source-parsers/jsoncpp/blob/master/doc/jsoncpp.dox
下面的Demo,可以实现 读取json字符串、创造json对象、输出json字符串。
主要的函数是这4个函数:
Json::StreamWriterBuilder,
Json::writeString
Json::CharReaderBuilder
Json::parseFromStream
#include <iostream> #include <string> #include "../include/json/json.h" using namespace std; // g++ demo1.cpp -I ../include ./lib_json/libjsoncpp.a -std=c++11 int main() { Json::Value objectRoot; objectRoot["id"] = 1234; objectRoot["name"] = "henry"; cout <<"------------StreamWriterBuilder------------"<<endl; Json::StreamWriterBuilder wbuilder; wbuilder["indentation"] = ""; // wbuilder["indentation"] = "\t"; std::string document = Json::writeString(wbuilder, objectRoot); cout <<"StreamWriterBuilder: "<<document<<endl; char strBuf[]="{ \"id\":666, \"name\":\"henryHe\"}"; cout <<"------------CharReaderBuilder------------"<<endl; std::istringstream iss(strBuf); ////必须得强制类型转换 Json::Value readValue; Json::CharReaderBuilder rbuilder; rbuilder["collectComments"] = false; std::string errs; bool ok = Json::parseFromStream(rbuilder, iss , &readValue, &errs); cout <<"ok: "<<ok<<endl; cout <<"id: "<<readValue["id"]<<endl; cout <<"name: "<<readValue["name"]<<endl; // const std::string rawJson = R"({"Age": 20, "Name": "colin"})"; // const int rawJsonLength = static_cast<int>(rawJson.length()); // cout << rawJsonLength<<endl; // cout << rawJson<<endl; cout <<"hello world"<<endl; return 0; }
相关推荐
linuxalienyan 2011-02-18
baijinswpu 2019-11-09
chinewwen 2011-09-02
abcx 2012-02-08
qianqianxiao 2019-07-01
朴有天虹 2019-06-20
frankwang 2011-07-30
张树刚 2017-04-06
疯狂的扣子 2017-03-13
89281943 2014-08-26
此处省略三千字 2011-06-15
pedily 2012-01-04