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;
}

相关推荐