jsoncpp使用

jsoncpp簡介

jsoncp是一個操作json類型的c++庫,可用於json串的解析與構造。其優點是語法簡單,但是效率不如rapidjson。
源碼下載鏈接:open-source-parsers/jsoncpp
Documention: JsonCpp documentation

安裝與使用

其中最簡單的方法是執行項目根目錄中的python腳本,構建頭文件和源文件。

  1. 在安裝Python環境的控制檯中進入jsoncpp項目根目錄,

  2. 執行命令:

python amalgamate.py
3. 將生成的dist目錄拷貝到自己的項目中,其中包源文件jsoncpp.cpp和頭文件json.h、json-forwards.h。

使用時只需要包含<json/json.h>即可

使用jsoncpp解析json串

基本步驟:

  1. 調用Json::Reader的parse方法,解析json串到Json::Value中.
  2. 使用[]或者get獲取對應key的value.
  3. 對value進行類型判斷,然後使用jsoncpp提供的轉化函數轉換成對應的值(調用asString等函數).
    jsoncpp中的類型判斷函數如下:
bool isNull() const;
bool isBool() const;
bool isInt() const;
bool isInt64() const;
bool isUInt() const;
bool isUInt64() const;
bool isIntegral() const;
bool isDouble() const;
bool isNumeric() const;
bool isString() const;       
bool isArray() const;
bool isObject() const;

jsoncpp中的類型轉化函數如下:

  const char* asCString() const; ///< Embedded zeroes could cause you trouble!
#if JSONCPP_USING_SECURE_MEMORY
  unsigned getCStringLength() const; // Allows you to understand the length of
                                     // the CString
#endif
  JSONCPP_STRING asString() const; ///< Embedded zeroes are possible.
  /** Get raw char* of string-value.
   *  \return false if !string. (Seg-fault if str or end are NULL.)
   */
  bool getString(char const** begin, char const** end) const;
#ifdef JSON_USE_CPPTL
  CppTL::ConstString asConstString() const;
#endif
  Int asInt() const;
  UInt asUInt() const;
#if defined(JSON_HAS_INT64)
  Int64 asInt64() const;
  UInt64 asUInt64() const;
#endif // if defined(JSON_HAS_INT64)
  LargestInt asLargestInt() const;
  LargestUInt asLargestUInt() const;
  float asFloat() const;
  double asDouble() const;
  bool asBool() const;

下面是具體的解析僞代碼示例(註釋行爲使用的deprecated的Json::Read類):

void parseJsonString(string & str)
{
    //Json::Reader json_reader;
    Json::CharReaderBuilder builer;
    builder["collectComments"] = false;
    Json::Value json_value;
    std::string errs;
    const char * p_str = str.c_str();
    Json::CharReader* reader = builder.newCharReader();
    //if(!json_reader.parse(p_str, p_str + str.size(), json_value, false) || (!json_value.isObject()))
    if(!reader->parse(p_str, p_str + str.size(), &json_value, &errs) || (!json_value.isObject()))
    {
        cout << "parse " << str << "fail" << endl;
        delete reader;
        return ;
    }

    Json::Value var = json_value["key"];
    if(var.isNull())
    {
        ...
    }else if(var.isObject)
    {
    	 cout << "var is a object" << endl;
        //continue to parse the object 
        ...
    }else if(var.isString())
    {
        cout << var.asString() << endl;
    }else if(var.isInt()){
		 ...
    }
    ...
    
    delete reader;
}

如果輸入的json內容位於文件的話,可以使用Json::CharReadBuilder來解析[需要將如下的std::cin替換成fstream變量]:

// Here, using a specialized Builder, we discard comments and
// record errors as we parse.
Json::CharReaderBuilder rbuilder;
rbuilder["collectComments"] = false;
std::string errs;
Json::Value root;
bool ok = Json::parseFromStream(rbuilder, std::cin, &root, &errs);

使用jsoncpp構造json串

構造示例代碼如下:

void constructJsonString(string & str)
{
    Json::Value root;
    Json::FastWriter writer;
    Json::Value element;
    element["name"] = "wang";
    root["key"] = element;
    str = writer.write(root);
    cout << str << endl;
 
}

在新的版本中FastWriter類被聲明爲deprecated,推薦使用StreamWriterBuilder,示例代碼如下:

 void constructJsonString1(string & str)
 {
     Json::Value root;
     Json::StreamWriterBuilder writerbuilder;
     Json::Value element;
     element["name"] = "wang";
     root["key"] = element;
     str = Json::writeString(writerbuilder, root);
     cout << str << endl;
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章