jsoncpp用法簡述


Jsoncpp是一個使用C++語言實現的面向對象的json庫。

Jsoncpp提供的接口中有3個核心類:ReaderWriterValue。

Reader類負責從字符串或者輸入流中加載JSON文檔,並進行解析,生成代表JSON檔的Value對象。 

Writer類負責將內存中的Value對象轉換成JSON文檔,可輸出到文件或者是字符串中。 

Value類的對象代表一個JSON值,既可以代表一個文檔,也可以代表文檔中一個值。 

 

一個JSON文檔的大致過程如下:  

//准備Json源數據,如讀取文檔:Std::string strdoc = readFromFile(… );

。。。

//生命頂級Value對象 

Json::Value root;

//聲明Reader對象

Json::Reader _reader;

  // 解析 json 文檔

_reader.paser(strdoc, root); 

 

Json::ValueType有8種,以下是定義。 enum Json::ValueType
Enumerator:
nullValue       'null' value
intValue     signed integer value
uintValue       unsigned integer value
realValue       double value
stringValue     UTF-8 string value.
booleanValue   bool value
arrayValue      array value (ordered list)
objectValue    object value (collection of name/value pairs).

static void printValueTree( FILE *fout, Json::Value &value, const std::string &path = "." ) 
{ 
switch ( value.type() ) 
{ 
case Json::nullValue:    
    fprintf( fout, "%s=null\n", path.c_str() );
    break;
case Json::intValue:
    fprintf( fout, "%s=%d\n", path.c_str(), value.asInt() );
    break;
case Json::uintValue:
    fprintf( fout, "%s=%u\n", path.c_str(), value.asUInt() );
    break;
case Json::realValue:
    fprintf( fout, "%s=%.16g\n", path.c_str(), value.asDouble() );
    break;
case Json::stringValue:
    fprintf( fout, "%s=\"%s\"\n", path.c_str(), value.asString().c_str() );
    break;
case Json::booleanValue:
    fprintf( fout, "%s=%s\n", path.c_str(), value.asBool() ? "true" : "false" );
    break;
case Json::arrayValue:
{
    fprintf( fout, "%s=[]\n", path.c_str() );
    int size = value.size();
    for ( int index =0; index < size; ++index )
    {
        static char buffer[16];
        sprintf( buffer, "[%d]", index );
        printValueTree( fout, value[index], path + buffer );
    }
}
break;
case Json::objectValue:
{
    fprintf( fout, "%s={}\n", path.c_str() );
    Json::Value::Members members( value.getMemberNames() );
    std::sort( members.begin(), members.end() );
    std::string suffix = *(path.end()-1) == '.' ? "" : ".";
    for ( Json::Value::Members::iterator it = members.begin(); it != members.end();         ++it )
    {
        const std::string &name = *it;
        printValueTree( fout, value[name], path + suffix + name );
    }
}
break;
default:
    break; 
} 
}

 

1) Json::Reader 是用於讀取Json對象的值。
    用法:

    Json::Value reader_object;
    Json::Reader reader;
    const char* reader_document = "{"path" : "/home/test.mp3","size" : 4000}";
    if (!reader.parse(reader_document, reader_object))
        return 0;
    std::cout << reader_object["path"] << std::endl;
    std::cout << reader_object["size"] << std::endl;
    結果:
    "/home/test.mp3"
    4000 

 

 2) 增加子節點

    Json::Value root;

    Json::Value leaf;

    ...

  root["leaf_node"] = leaf;

 

3) 值為數組的,通過對同一key逐個append方式追加:

    root["key_array"].append("the string");  //元素值類型為字符串

    root["key_array"].append(20);                  //元素值類型同時可為int等等

 

4) 解析數組值

    JArray = root["key_array"];
    for ( unsigned int i = 0; i < JArray.size(); i++ )
    {
        cout << "JSON array values: " << JArray[i].asString() << endl;
    }

 

5) 注意操作符[]的定義:

Value & Json::Value::operator[] ( const StaticString & key )

Access an object value by name, create a null member if it does not exist.

因此但凡使用[]或者通過get()間接使用[]的,若原來元素不存在,都將增加一個value為null的新元素。

事先判斷某名稱的元素是否存在可以使用 isMember():

if(infoRoot.isObject() && infoRoot.isMember("error"))
...

  

 

二. 通過使用Writer將Value轉換為JSON文檔(string):

1) Json::FastWriter用來快速輸出Json對象的值,即

    用法:
      Json::FastWriter writer;
      std::cout << writer.write(json_media)<< std::endl;
    結果:
    {"isArray":["test1","test2"],"isBoolean":true,"isDouble":0.25,"size":4000,"isObject": {},"path":"/home/mp3/test.mp3"}


2) Json::StyledWriter用來格式化輸出Json對象的值。

    用法:
      Json::StyledWriter writer;
      std::cout << writer.write(json_media) << std::endl;
    結果:
    {
       "isArray" : [ "test1", "test2" ],
       "isBoolean" : true,
       "isDouble" : 0.24,
       "size" : 4000,
       "isObject" : {},
       "path" : "/home/mp3/test.mp3"
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM