jsoncpp基礎

jsoncpp是常用的C++語言JSON解析庫,它主要包含三個class:Value、Reader、Writer。

下面根據自己查到的資料等總結其用法(使用時 #include “json/json.h”):
1.Value
因爲是表示各種類型的對象,因此自然就是最基本、最重要的class。下面用簡單的代碼看看它怎麼用,真的很方便的:


Json::Value temp;                      // 臨時對象temp
temp["name"] = Json::Value("Alieen");  //name是Alieen
temp["age"] = Json::Value(18);         //age是18

root表示整個json對象

Json::Value root;               // 表示整個 json 對象

root["str"] = Json::Value("value_string");         
// 新建一個 Key(名爲str),賦予字符串值:"value_string"。

root["num"] = Json::Value(12345);            
// 新建一個 Key(名爲num),賦予數值:12345。

root["double"] = Json::Value(12.345);            
// 新建一個 Key(名爲double),賦予 double 值:12.345。

root["boolean"] = Json::Value(false);             
// 新建一個 Key(名爲boolean),賦予bool值:false。

root["key_object"] = temp;                          
// 新建一個 Key(名爲key_object),賦予 Json::Value temp 對象值。

root["key_array"].append("array_string");             
// 新建一個 Key(名爲key_array),類型爲數組,對第一個元素賦值爲字符串:"array_string"。

root["key_array"].append(1234);                           
//爲數組 key_array 賦值,對第二個元素賦值爲:1234。
//注:數組中可以有不同類型的值**

Json::ValueType type = root.type();                       
// 獲得 root 的類型,此處爲 objectValue 類型。

2.Reader
將json文件流或字符串解析到Json::Value, 主要函數有Parse.

 Json::Reader reader;
 Json::Value json_object;
 const char* json_document = "{\"age\" : 18,\"name\" : \"Alieen\"}";
 if (!reader.parse(json_document, json_object))
    return 0;
 std::cout << json_object["name"] << std::endl;
 std::cout << json_object["age"]  << std::endl;

輸出結果(待檢驗):

Alieen
18

3.Writer
與Json::Reader相反,是將Json::Value轉化成字符串流。
它的兩個子類:
①Json::FastWriter(不帶格式json)
②Json::StyleWriter(帶格式json)
Jsoncpp 的 Json::Writer 類是一個純虛類,不能直接使用。使用 Json::Writer 的子類:Json::FastWriter、Json::StyledWriter、Json::StyledStreamWriter。

Json::FastWriter fast_writer;
std::cout << fast_writer.write(root) << std::endl;

輸出:

{"key_array":["str",1234],"key_boolean":false,"key_double":12.3450,"key_number":12345,"key_object":{"age":18,"name":"Alieen"},"key_string":"value_string"}

用 Json::StyledWriter 是格式化後的 json,下面我們來看看 Json::StyledWriter 是怎樣格式化的。

Json::StyledWriter styled_writer;
std::cout << styled_writer.write(root) << std::endl;

輸出:

{
   "key_array" : [ "str", 1234 ],
   "key_boolean" : false,
   "key_double" : 12.3450,
   "key_number" : 12345,
   "key_object" : {
      "age" : 18,
      "name" : "Alieen"
   },
   "key_string" : "value_string"
}

(好多blog因爲copy&paste都有這句話:“ Json::Value 只能處理 ANSI 類型的字符串,如果 C++ 程序是用 Unicode 編碼的,最好加一個 Adapt 類來適配。”之前寫別的程序遇到過這種問題,也試着查過這個問題,但是未果,暫且隨它去吧,有bug了再說…)


下面是一些實例:(參考)
1.文件讀寫


#include <iostream>
#include <fstream>

#include "json.h"

static bool write_jscon( const char * json_file, const Json:: Value & val)
{
           if ( json_file == NULL)
                    return false;

          std:: ofstream out_json( json_file);
           if (!out_json)
                    return false;

          Json:: StyledStreamWriter writer;
          writer.write(out_json, val);

          out_json.close();

           return true;
}

static bool read_json(const char *json_file , Json::Value &val )
{
          std:: ifstream in_file( json_file, std:: ios::binary);
           if (! json_file)
                    return false;

           if (!Json:: Reader().parse(in_file, val))
          {
                   in_file.close();
                    return false;
          }

          in_file.close();
           return true;
}

2.從字符串中讀取JSON

#include <iostream 
#include "json/json.h" 
using namespace std;

int main()
{
    //字符串
    const char* str = 
    "{\"praenomen\":\"Gaius\",\"nomen\":\"Julius\",\"cognomen\":\"Caezar\"," "\"born\":-100,\"died\":-44}";

    Json::Reader reader;
    Json::Value root;

    //從字符串中讀取數據
    if(reader.parse(str,root))
    {
        string praenomen = root["praenomen"].asString();
        string nomen = root["nomen"].asString();
        string cognomen = root["cognomen"].asString();
        int born = root["born"].asInt();
        int died = root["died"].asInt();

        cout << praenomen + " " + nomen + " " + cognomen
            << " was born in year " << born 
            << ", died in year " << died << endl;
    }

    return 0;
}

3.從文件中讀取json
文件PersonalInfo.json(一個存儲了JSON格式字符串的文件)

{
    "name":"Tsybius",
    "age":23,
    "sex_is_male":true,
    "partner":
    {
        "partner_name":"Galatea",
        "partner_age":21,
        "partner_sex_is_male":false
    },
    "achievement":["ach1","ach2","ach3"]
}

a.cpp

#include <iostream>
#include <fstream>

#include "json/json.h"

using namespace std;

int main()
{
    Json::Reader reader;
    Json::Value root;

    //從文件中讀取
    ifstream is;
    is.open("PersonalInfo.json", ios::binary);

    if(reader.parse(is,root))
    {
        //讀取根節點信息
        string name = root["name"].asString();
        int age = root["age"].asInt();
        bool sex_is_male = root["sex_is_male"].asBool();

        cout << "My name is " << name << endl;
        cout << "I'm " << age << " years old" << endl;
        cout << "I'm a " << (sex_is_male ? "man" : "woman") << endl;

        //讀取子節點信息
        string partner_name = root["partner"]["partner_name"].asString();
        int partner_age = root["partner"]["partner_age"].asInt();
        bool partner_sex_is_male = root["partner"]["partner_sex_is_male"].asBool();

        cout << "My partner's name is " << partner_name << endl;
        cout << (partner_sex_is_male ? "he" : "she") << " is "
            << partner_age << " years old" << endl;

        //讀取數組信息
        cout << "Here's my achievements:" << endl;
        for(int i = 0; i < root["achievement"].size(); i++)
        {
            string ach = root["achievement"][i].asString();
            cout << ach << '\t';
        }
        cout << endl;

        cout << "Reading Complete!" << endl;
    }

    is.close();

    return 0;
}

4.將信息保存爲json格式
a.cpp

#include <iostream>
#include <fstream>

#include "json/json.h"

using namespace std;

int main()
{
    //根節點
    Json::Value root;

    //根節點屬性
    root["name"] = Json::Value("Tsybius");
    root["age"] = Json::Value(23);
    root["sex_is_male"] = Json::Value(true);

    //子節點
    Json::Value partner;

    //子節點屬性
    partner["partner_name"] = Json::Value("Galatea");
    partner["partner_age"] = Json::Value(21);
    partner["partner_sex_is_male"] = Json::Value(false);

    //子節點掛到根節點上
    root["partner"] = Json::Value(partner);

    //數組形式
    root["achievement"].append("ach1");
    root["achievement"].append("ach2");
    root["achievement"].append("ach3");

    //直接輸出
    cout << "FastWriter:" << endl;
    Json::FastWriter fw;
    cout << fw.write(root) << endl << endl;

    //縮進輸出
    cout << "StyledWriter:" << endl;
    Json::StyledWriter sw;
    cout << sw.write(root) << endl << endl;

    //輸出到文件
    ofstream os;
    os.open("PersonalInfo");
    os << sw.write(root);
    os.close();

    return 0;
}

生成的文件PersonalInfo.json

{
   "achievement" : [ "ach1", "ach2", "ach3" ],
   "age" : 23,
   "name" : "Tsybius",
   "partner" : {
      "partner_age" : 21,
      "partner_name" : "Galatea",
      "partner_sex_is_male" : false
   },
   "sex_is_male" : true
}

代碼來源:
http://my.oschina.net/Tsybius2014/blog/289527

發佈了17 篇原創文章 · 獲贊 6 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章