zoukankan      html  css  js  c++  java
  • 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"] = "	";
        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;
    }

    说明:项目中的  libjsoncpp.a  是我根据 JsonCpp 工程的源码编译的 库。

    直接下载JsonCpp工程,解压之后,执行

    cmake ./  
    
    make -f Makefile 

    如果没有安装CMake,请看这里:https://www.cnblogs.com/music-liang/p/12900511.html

  • 相关阅读:
    php注册、登录界面的制作
    php将表单中数据传入到数据库
    数据操作
    Hibernate入门(五)---------事务管理
    MySQL事务(学习笔记)
    Hibernate入门(四)---------一级缓存
    Hibernate入门(三)
    反射demo(拷贝一个对象)
    反射学习小结
    Hibernate入门(二)——hibernateAPI详解
  • 原文地址:https://www.cnblogs.com/music-liang/p/12904554.html
Copyright © 2011-2022 走看看