C++使用 jsoncpp 解析json数据

整合自网路

一、安装的方法

1、安装 scons

  下载地址:http://sourceforge.net/projects/scons/files/scons/2.1.0/scons-2.1.0.tar.gz/download

  百度网盘:链接:https://pan.baidu.com/s/1tW57c9s3iCeoDi4OIDyEPQ 密码:2wd5

  解压:tar -zvxf scons-2.1.0.tar.gz

  进入到解压目录scons-2.1.0 执行命令:

    sudo python setup.py install

2、安装 Jsoncpp

  下载地址:http://sourceforge.net/projects/jsoncpp/

  解压:tar -zvxf jsoncpp-src-0.5.0.tar.gz

  进入到jsoncpp解压目录下,执行命令:

  sudo scons platform=linux-gcc

  将/jsoncpp-src-0.5.0/include/目录下的json文件夹拷贝到 /usr/local/include/

  将jsoncpp-src-0.5.0/libs/linux-gcc-4.9.1/目录下的libjson_linux-gcc-4.9.1_libmt.a 拷贝到 /usr/local/lib/ 下,并为了方便使用,将其重命名为libjson.a

二、使用方法

1、使用 parse 接口进行转化

Json::Reader *pJsonParser = new Json::Reader();
string strJson = "1111 {}";        //不合法json
 
Json::Value tempVal;
  
if(!pJsonParser->parse(strJson, tempVal)){
    cout << "parse error" << endl;
    return -1;
}
string name = tempVal["name"].asString();

2、数组解析

Json::Reader *pJsonParser = new Json::Reader();
string strJson = "{\"name\":\"tom\",\"sex\":\"男\",\"age\":\"24\",\"friends\":[{\"name\":\"chen\',\'sex\':\'男\"},{\"name\":\"li\",\"sex\":\"女\"}]}";

Json::Value tempVal;
   
if(!pJsonParser->parse(strJson, tempVal)){
        return -1;
}
Json::Value friends = tempVal["friends"];
for(int i = 0;i < friends.size();i++){
  cout << friends[i]["name"].asString() << endl;
}
 

3、先进行类型判断

if(tempVal["name"].isInt()){
     int name = tempVal["name"].asInt();
}

 

posted @ 2018-08-15 09:22  oftenlin  阅读(7181)  评论(0编辑  收藏  举报