JsonCpp使用方法详解

摘要:
Jsoncpp是C++解析JSON字符串的常用解析库之一。jsoncpp:Json::Value:中的主要类可以表示所有支持的类型,例如int、double、string、object、array等=)、Node操作和其他函数。以下Json文件示例Json:{“encoding”:“UTF-8”,“plugins”:[“python”,“c++”,“ruby”],“indent”:{“length”:3,“use_space”:true}“tab”:null}使用Json::Reader解析Json文件:Json::Valueroot;Json::阅读器;std::ifstreamifs;//openfile示例。Jsonif(!简单地说,FastWriter是无格式的写作。这样的Json看起来非常凌乱和无格式,而StyledWriter是格式化的写作,看起来很友好。

JSON全称为JavaScript ObjectNotation,它是一种轻量级的数据交换格式,易于阅读、编写、解析。jsoncpp是c++解析JSON串常用的解析库之一。

jsoncpp中主要的类:

Json::Value:可以表示所有支持的类型,如:int , double ,string , object, array等。其包含节点的类型判断(isNull,isBool,isInt,isArray,isMember,isValidIndex等),类型获取(type),类型转换(asInt,asString等),节点获取(get,[]),节点比较(重载<,<=,>,>=,==,!=),节点操作(compare,swap,removeMember,removeindex,append等)等函数。

Json::Reader:将文件流或字符串创解析到Json::Value中,主要使用parse函数。Json::Reader的构造函数还允许用户使用特性Features来自定义Json的严格等级。

Json::Writer:与JsonReader相反,将Json::Value转换成字符串流等,Writer类是一个纯虚类,并不能直接使用。在此我们使用 Json::Writer 的子类:Json::FastWriter(将数据写入一行,没有格式),Json::StyledWriter(按json格式化输出,易于阅读)。

Json::Reader可以通过对Json源目标进行解析,得到一个解析好了的Json::Value,通常字符串或者文件输入流可以作为源目标。


如下Json文件example.json:

  1.  
    {
  2.  
    "encoding" : "UTF-8",
  3.  
    "plug-ins" : [
  4.  
    "python",
  5.  
    "c++",
  6.  
    "ruby"
  7.  
    ],
  8.  
    "indent" : { "length" : 3, "use_space": true }
  9.  
    "tab":null
  10.  
    }


使用Json::Reader对Json文件进行解析:

  1.  
    Json::Value root;
  2.  
    Json::Reader reader;
  3.  
    std::ifstream ifs("example.json");//open file example.json
  4.  
     
  5.  
    if(!reader.parse(ifs, root)){
  6.  
    // fail to parse
  7.  
    }
  8.  
    else{
  9.  
    // success
  10.  
    std::cout<<root["encoding"].asString()<<endl;
  11.  
    std::cout<<root["indent"]["length"].asInt()<<endl;
  12.  
    }


使用Json::Reader对字符串进行解析:

  1.  
    Json::Value root;
  2.  
    Json::Reader reader;
  3.  
    const char* s = "{"uploadid": "UP000000","code": 100,"msg": "","files": ""}";
  4.  
    if(!reader.parse(s, root)){
  5.  
    // "parse fail";
  6.  
    }
  7.  
    else{
  8.  
    std::cout << root["uploadid"].asString();//print "UP000000"
  9.  
    }


Json::Writer 和 Json::Reader相反,是把Json::Value对象写到string对象中,而且Json::Writer是个抽象类,被两个子类Json::FastWriter和Json::StyledWriter继承。 
简单来说FastWriter就是无格式的写入,这样的Json看起来很乱没有格式,而StyledWriter就是带有格式的写入,看起来会比较友好。

  1.  
    Json::Value root;
  2.  
    Json::Reader reader;
  3.  
    Json::FastWriter fwriter;
  4.  
    Json::StyledWriter swriter;
  5.  
     
  6.  
    if(! reader.parse("example.json", root)){
  7.  
    // parse fail
  8.  
    return 0;
  9.  
    }
  10.  
    std::string str = fwriter(root);
  11.  
    std::ofstream ofs("example_fast_writer.json");
  12.  
    ofs << str;
  13.  
    ofs.close();
  14.  
     
  15.  
    str = swriter(root);
  16.  
    ofs.open("example_styled_writer.json");
  17.  
    ofs << str;
  18.  
    ofs.close();
  19.  
     
  20.  
    结果1:example_styled_writer.json:
  21.  
    {
  22.  
    "encoding" : "UTF-8",
  23.  
    "plug-ins" : [
  24.  
    "python",
  25.  
    "c++",
  26.  
    "ruby"
  27.  
    ],
  28.  
    "indent" : { "length" : 3, "use_space": true }
  29.  
    "tab":null
  30.  
    }
  31.  
     
  32.  
    结果2:example_fast_writer.json:
  33.  
    {"encoding" : "UTF-8","plug-ins" : ["python","c++","ruby"],"indent" : { "length" : 3, "use_space": true}}


Json其它函数的应用:
1、判断KEY值是否存在:

  1.  
    if(root.isMember("encoding")){
  2.  
    std::cout<<"encoding is a member"<<std::endl;
  3.  
    }
  4.  
    else{
  5.  
    std::cout<<"encoding is not a member"<<std::endl;
  6.  
    }


2、判断Value是否为null:

if(root["tab"].isNull()){
    std::cout << "isNull" <<std::endl;//print isNull
}

完整例子使用举例来自于CSDN下载网友的程序:

源码下载地址:http://download.csdn.net/download/woniu211111/9966907

  1.  
    /********************************************************
  2.  
    Copyright (C), 2016-2017,
  3.  
    FileName: main
  4.  
    Author: woniu201
  5.  
    Email: wangpengfei.201@163.com
  6.  
    Created: 2017/09/06
  7.  
    Description:use jsoncpp src , not use dll, but i also provide dll and lib.
  8.  
    ********************************************************/
  9.  
     
  10.  
    #include "stdio.h"
  11.  
    #include <string>
  12.  
    #include "jsoncpp/json.h"
  13.  
     
  14.  
    using namespace std;
  15.  
     
  16.  
    /************************************
  17.  
    @ Brief: read file
  18.  
    @ Author: woniu201
  19.  
    @ Created: 2017/09/06
  20.  
    @ Return: file data
  21.  
    ************************************/
  22.  
    char *getfileAll(char *fname)
  23.  
    {
  24.  
    FILE *fp;
  25.  
    char *str;
  26.  
    char txt[1000];
  27.  
    int filesize;
  28.  
    if ((fp=fopen(fname,"r"))==NULL){
  29.  
    printf("open file %s fail ",fname);
  30.  
    return NULL;
  31.  
    }
  32.  
     
  33.  
    /*
  34.  
    获取文件的大小
  35.  
    ftell函数功能:得到流式文件的当前读写位置,其返回值是当前读写位置偏离文件头部的字节数.
  36.  
    */
  37.  
    fseek(fp,0,SEEK_END);
  38.  
    filesize = ftell(fp);
  39.  
     
  40.  
    str=(char *)malloc(filesize);
  41.  
    str[0]=0;
  42.  
     
  43.  
    rewind(fp);
  44.  
    while((fgets(txt,1000,fp))!=NULL){
  45.  
    strcat(str,txt);
  46.  
    }
  47.  
    fclose(fp);
  48.  
    return str;
  49.  
    }
  50.  
     
  51.  
    /************************************
  52.  
    @ Brief: write file
  53.  
    @ Author: woniu201
  54.  
    @ Created: 2017/09/06
  55.  
    @ Return:
  56.  
    ************************************/
  57.  
    int writefileAll(char* fname,const char* data)
  58.  
    {
  59.  
    FILE *fp;
  60.  
    if ((fp=fopen(fname, "w")) == NULL)
  61.  
    {
  62.  
    printf("open file %s fail ", fname);
  63.  
    return 1;
  64.  
    }
  65.  
     
  66.  
    fprintf(fp, "%s", data);
  67.  
    fclose(fp);
  68.  
     
  69.  
    return 0;
  70.  
    }
  71.  
     
  72.  
    /************************************
  73.  
    @ Brief: parse json data
  74.  
    @ Author: woniu201
  75.  
    @ Created: 2017/09/06
  76.  
    @ Return:
  77.  
    ************************************/
  78.  
    int parseJSON(const char* jsonstr)
  79.  
    {
  80.  
    Json::Reader reader;
  81.  
    Json::Value resp;
  82.  
     
  83.  
    if (!reader.parse(jsonstr, resp, false))
  84.  
    {
  85.  
    printf("bad json format! ");
  86.  
    return 1;
  87.  
    }
  88.  
    int result = resp["Result"].asInt();
  89.  
    string resultMessage = resp["ResultMessage"].asString();
  90.  
    printf("Result=%d; ResultMessage=%s ", result, resultMessage.c_str());
  91.  
     
  92.  
    Json::Value & resultValue = resp["ResultValue"];
  93.  
    for (int i=0; i<resultValue.size(); i++)
  94.  
    {
  95.  
    Json::Value subJson = resultValue[i];
  96.  
    string cpuRatio = subJson["cpuRatio"].asString();
  97.  
    string serverIp = subJson["serverIp"].asString();
  98.  
    string conNum = subJson["conNum"].asString();
  99.  
    string websocketPort = subJson["websocketPort"].asString();
  100.  
    string mqttPort = subJson["mqttPort"].asString();
  101.  
    string ts = subJson["TS"].asString();
  102.  
     
  103.  
    printf("cpuRatio=%s; serverIp=%s; conNum=%s; websocketPort=%s; mqttPort=%s; ts=%s ",cpuRatio.c_str(), serverIp.c_str(),
  104.  
    conNum.c_str(), websocketPort.c_str(), mqttPort.c_str(), ts.c_str());
  105.  
    }
  106.  
    return 0;
  107.  
    }
  108.  
     
  109.  
    /************************************
  110.  
    @ Brief: create json data
  111.  
    @ Author: woniu201
  112.  
    @ Created: 2017/09/06
  113.  
    @ Return:
  114.  
    ************************************/
  115.  
    int createJSON()
  116.  
    {
  117.  
    Json::Value req;
  118.  
    req["Result"] = 1;
  119.  
    req["ResultMessage"] = "200";
  120.  
     
  121.  
    Json::Value object1;
  122.  
    object1["cpuRatio"] = "4.04";
  123.  
    object1["serverIp"] = "42.159.116.104";
  124.  
    object1["conNum"] = "1";
  125.  
    object1["websocketPort"] = "0";
  126.  
    object1["mqttPort"] = "8883";
  127.  
    object1["TS"] = "1504665880572";
  128.  
    Json::Value object2;
  129.  
    object2["cpuRatio"] = "2.04";
  130.  
    object2["serverIp"] = "42.159.122.251";
  131.  
    object2["conNum"] = "2";
  132.  
    object2["websocketPort"] = "0";
  133.  
    object2["mqttPort"] = "8883";
  134.  
    object2["TS"] = "1504665896981";
  135.  
     
  136.  
    Json::Value jarray;
  137.  
    jarray.append(object1);
  138.  
    jarray.append(object2);
  139.  
     
  140.  
    req["ResultValue"] = jarray;
  141.  
     
  142.  
    Json::FastWriter writer;
  143.  
    string jsonstr = writer.write(req);
  144.  
     
  145.  
    printf("%sn", jsonstr.c_str());
  146.  
     
  147.  
    writefileAll("createJson.json", jsonstr.c_str());
  148.  
    return 0;
  149.  
    }
  150.  
     
  151.  
    int main()
  152.  
    {
  153.  
    /*读取Json串,解析Json串*/
  154.  
    char* json = getfileAll("parseJson.json");
  155.  
    parseJSON(json);
  156.  
    printf("=============================== ");
  157.  
     
  158.  
    /*组装Json串*/
  159.  
    createJSON();
  160.  
     
  161.  
    getchar();
  162.  
    return 1;
  163.  
    }


参考:

http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html

http://blog.csdn.net/yc461515457/article/details/52749575

免责声明:文章转载自《JsonCpp使用方法详解》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇如何从网页安装群晖NAS并设置静态IPWindows事件ID大全下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

C++ 使用Json时,VS2010添加jsoncpp

一编译链接 1在相应官网下载jsoncpp 2解压得到jsoncpp-src-0.5.0文件 3打开jsoncpp-src-0.5.0->makefiles->vs71->jsoncpp.sln 4转换项目为VS2010格式 5选择debug模式 6在“解决方案资源管理器”中右击lib_json选择->仅用于项目->仅生成...

序列化对象C++对象的JSON序列化与反序列化探索

新手发帖,很多方面都是刚入门,有错误的地方请大家见谅,欢迎批评指正     一:背景     作为一名C++开发人员,我始终很期待能够像C#与JAVA那样,可以省力的进行对象的序列化与反序列化,但到现在为止,还没有找到相对完美的处理方案。     本文旨在抛砖引玉,期待有更好的处理方案;同时向大家追求帮助,处理本文中未处理的问题。      二:相干技术介...

使用 C++ 处理 JSON 数据交换格式 .

使用C++ 处理JSON 数据交换格式 一、摘要 JSON 的全称为:JavaScript Object Notation,顾名思义,JSON 是用于标记Javascript 对象的,JSON 官方的解释为:JSON 是一种轻量级的数据传输格式。 本文并不详细介绍JSON 本身的细节,旨在讨论如何使用C++ 语言来处理JSON。关于JSON 更具体的信息,...

C++ 解析Json——jsoncpp

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,和xml类似,本文主要对VS2008中使用Jsoncpp解析json的方法做一下记录。Jsoncpp是个跨平台的开源库,下载地址:http://sourceforge.net/projects/jsoncpp/。 方法一:使用Jsoncpp生成的lib文件 解压上...

JsonCpp使用优化

JsonCpp使用优化 « 搜索技术博客-淘宝 十一 JsonCpp使用优化恨少 最近一个项目在使用JsonCpp,JsonCpp简洁易用的接口让人印象深刻。但是在实际使用过程中,我发现JsonCpp的性能却不尽如人意,所以想着方法优化下性能。 代码理解 1、JsonCpp中一切都是Value,Value用union指向自己保存的数据。Value...

jsoncpp解析拼装数组

Cocos2d-x添加jsoncpp应该资料都有了,今天来讲讲数组的解析和拼装~ [cpp] view plain copy      int main()   {   数组创建与分析:   例子一:   string strValue = "{"ldh":"001","gfc":"002","yyj":"003","andy":["005","12...