1. 程式人生 > >Jsoncpp 使用方法大全

Jsoncpp 使用方法大全

com str n-1 view int nco encode rec 輕量

Jsoncpp 使用方法大全

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

Json(JavaScript Object Notation )是一種輕量級的數據交換格式。簡而言之,Json組織形式就和python中的字典, C/C++中的map一樣,是通過key-value對來組織的,key是任意一個唯一字符串,value可以是bool,int,string 或者嵌套的一個json。關於Json 格式可以參考官方網站。
Jsoncpp 是一個用來處理 Json文本的開源C++庫,下面就簡單介紹使用Jsoncpp對Json文件的常見操作。


Jsoncpp 常用變量介紹

在Jsoncpp中,有幾個常用的變量特別重要,首先介紹一下。

Json::Value

Json::Value 用來表示Json中的任何一種value抽象數據類型,具體來說,Json中的value可以是一下數據類型:

  • 有符號整數 signed integer [range: Value::minInt - Value::maxInt]
  • 無符號整數 unsigned integer (range: 0 - Value::maxUInt)
  • 雙精度浮點數 double
  • 字符串 UTF-8 string
  • 布爾型 boolean
  • 空 ‘null’
  • 一個Value的有序列表 an ordered list of Value
  • collection of name/value pairs (javascript object)

可以通過[]的方法來取值。

//Examples:
Json::Value null_value; // null
Json::Value arr_value(Json::arrayValue); // []
Json::Value obj_value(Json::objectValue); // {}

Json::Reader

Json::Reader可以通過對Json源目標進行解析,得到一個解析好了的Json::Value,通常字符串或者文件輸入流可以作為源目標。

假設現在有一個example.json文件

{
    "encoding" : "UTF-8",
    "plug-ins" : [
        "python",
        "c++",
        "ruby"
        ],
    "indent" : { "length" : 3, "use_space": true }
}

使用Json::Reader對Json文件進行解析:

bool parse (const std::string &document, Value &root, bool collectComments=true)
bool parse (std::istream &is, Value &root, bool collectComments=true)


Json::Value root;
Json::Reader reader;
std::ifstream ifs("example.json");//open file example.json

if(!reader.parse(ifs, root)){
   // fail to parse
}
else{
   // success
   std::cout<<root["encoding"].asString()<<endl;
   std::cout<<root["indent"]["length"].asInt()<<endl;
}

使用Json::Reader對字符串進行解析

bool Json::Reader::parse ( const char * beginDoc,
        const char * endDoc,
        Value & root,
        bool collectComments = true 
    )   

  Json::Value root;
  Json::Reader reader;
  const char* s = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}"; 
  if(!reader.parse(s, root)){
    // "parse fail";
  }
  else{
      std::cout << root["uploadid"].asString();//print "UP000000"
  }

Json::Writer

Json::Writer 和 Json::Reader相反,是把Json::Value對象寫到string對象中,而且Json::Writer是個抽象類,被兩個子類Json::FastWriter和Json::StyledWriter繼承。
簡單來說FastWriter就是無格式的寫入,這樣的Json看起來很亂沒有格式,而StyledWriter就是帶有格式的寫入,看起來會比較友好。

Json::Value root;
Json::Reader reader;
Json::FastWriter fwriter;
Json::StyledWriter swriter;

if(! reader.parse("example.json", root)){
// parse fail
    return 0;
}
std::string str = fwriter(root);
std::ofstream ofs("example_fast_writer.json");
ofs << str;
ofs.close();

str = swriter(root);
ofs.open("example_styled_writer.json");
ofs << str;
ofs.close();

結果:
example_styled_writer.json

{
    "encoding" : "UTF-8",
    "plug-ins" : [
        "python",
        "c++",
        "ruby"
        ],
    "indent" : { "length" : 3, "use_space": true }
}

example_fast_writer.json

{"encoding" : "UTF-8","plug-ins" : ["python","c++","ruby"],"indent" : { "length" : 3, "use_space": true}}


Jsoncpp 其他操作

通過前面介紹的Json::value, Json::Reader, Json::Reader 可以實現對Json文件的基本操作,下面介紹一些其他的常用的操作。

判斷key是否存在

bool Json::Value::isMember ( const char * key) const

Return true if the object has a member named key.

Note
    ‘key‘ must be null-terminated. 

bool Json::Value::isMember ( const std::string &  key) const
bool Json::Value::isMember ( const char* key, const char * end ) const

// print "encoding is a member"
if(root.isMember("encoding")){
    std::cout<<"encoding is a member"<<std::endl;
}
else{
    std::cout<<"encoding is not a member"<<std::endl;
}

// print "encode is not a member"
if(root.isMember("encode")){
    std::cout<<"encode is a member"<<std::endl;
}
else{
    std::cout<<"encode is not a member"<<std::endl;
}

判斷Value是否為null

首先要給example.json添加一個key-value對:

{
    "encoding" : "UTF-8",
    "plug-ins" : [
        "python",
        "c++",
        "ruby"
    ],
    "indent" : { "length" : 3, "use_space": true },
    "tab-length":[],
    "tab":null
}

判斷是否為null的成員函數

bool Json::Value::isNull ( ) const

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

if(root.isMember("tab-length")){//true
    if(root["tab-length"].isNull()){
      std::cout << "isNull" << std::endl;
    }
    else std::cout << "not Null"<<std::endl;
    // print "not Null", there is a array object([]), through this array object is empty
    std::cout << "empty: " << root["tab-length"].empty() << std::endl;//print empty: 1
    std::cout << "size: " << root["tab-length"].size() << std::endl;//print size: 0
  }

另外值得強調的是,Json::Value和C++中的map有一個共同的特點,就是當你嘗試訪問一個不存在的 key 時,會自動生成這樣一個key-value默認為null的值對。也就是說

 root["anything-not-exist"].isNull(); //false
 root.isMember("anything-not-exist"); //true

總結就是要判斷是否含有key,使用isMember成員函數,value是否為null使用isNull成員函數,value是否為空可以用empty() 和 size()成員函數。

得到所有的key

typedef std::vector<std::string> Json::Value::Members

Value::Members Json::Value::getMemberNames ( ) const

Return a list of the member names.

If null, return an empty list.

Precondition
    type() is objectValue or nullValue 

Postcondition
    if type() was nullValue, it remains nullValue 

可以看到Json::Value::Members實際上就是一個值為string的vector,通過getMemberNames得到所有的key。

刪除成員

Value Json::Value::removeMember( const char* key)   

Remove and return the named member.
Do nothing if it did not exist.

Returns
    the removed Value, or null. 

Precondition
    type() is objectValue or nullValue 

Postcondition
    type() is unchanged 

Value Json::Value::removeMember( const std::string & key)   

bool Json::Value::removeMember( std::string const &key, Value *removed)         

Remove the named map member.
Update ‘removed‘ iff removed.

Parameters
    key may contain embedded nulls.

Returns
    true iff removed (no exceptions) 


參考

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

Jsoncpp 使用方法大全