jsoncpp一个例子

来源:互联网 发布:宿州云计算数据机房 编辑:程序博客网 时间:2024/06/15 13:09

关于json的信息可以去看百度百科http://baike.baidu.com/view/136475.htm。

本文写的是,如何使用c++读取json的数据,使用jsoncpp库。

先附上代码,之后说明下jsoncpp的使用。

// g++ -g -Wall -o test_json test_json.cpp -I./include -L./lib -ljson#include <string>#include "json/json.h"using namespace std;int main() {{  // one data  cout << endl << "example 1:" << endl;  string test = "{\"id\":1,\"name\":\"hello\"}";  Json::Reader reader;  Json::Value value;  if (reader.parse(test, value)) {    int id = value["id"].asInt();    string name = value["name"].asString();    cout << id << " " << name << endl;  } else {    cout << "parse error" << endl;  }}{  // more data  cout << endl << "example 2:" << endl;  string test = "{\"array\":[{\"id\":1,\"name\":\"hello\"},{\"id\":2,\"name\":\"world\"}]}";  Json::Reader reader;  Json::Value value;  if (reader.parse(test, value)) {    const Json::Value arrayObj = value["array"];    for (size_t i=0; i<arrayObj.size(); i++) {      int id = arrayObj[i]["id"].asInt();      string name = arrayObj[i]["name"].asString();      cout << id << " " << name << endl;    }  } else {    cout << "parse error" << endl;  }}  return 0;}

里面有2个例子,第1个:读取一个数据,第2个:读取多个数据。

编译方法见代码第一行。


jsoncpp的使用

(1)安装jsoncpp:首先从http://www.scons.org/下载tar -zxvf scons-2.0.1.tar.gz并解压,从http://sourceforge.net/projects/jsoncpp/下载jsoncpp-src-0.5.0.tar.gz并解压,设置环境变量:

 export MYSCONS=/xxxxx/scons-2.1.0

 export SCONS_LIB_DIR=$MYSCONS/engine

编译jsoncpp:

 cd jsoncpp-src-0.5.0

python $MYSCONS/script/scons platform=linux-gcc

编译生成的.a在./libs/linux-gcc-xxx/

编译时指定lib和include即可。

(2)不安装jsoncpp:可以参考http://download.csdn.net/detail/hbuxiaoshe/5099819。

tar包中内置了jsoncpp的静态库(.a)和include(.h)文件,不需安装,解压即可编译,test_json.cpp和编译同上面。

原创粉丝点击