jsoncpp一個例子

關於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和編譯同上面。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章