1. 程式人生 > >JsonCpp 用法簡介

JsonCpp 用法簡介

JsonCpp 用法簡介

jsoncpp 主要包含三種類型 Value Writer Reader

Value

使用例項

#include <json/json.h>
#include <iostream>

using namespace std;

/*-----------------------------------------------------------------------
使用type()來獲取型別:
Json::ValueType type = V["nullValue"].type();

包括下列型別:
enum ValueType
{
    nullValue = 0, ///< '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).
};
/------------------------------------------------------------------------*/
int main(int argc, char** argv) { Json::Value V; V["nullValue"]; V["intValue"] = -1; V["uintValue"] = 2; V["realValue"] = 3.14; V["stringValue"] = "Hello World"; V["booleanValue"] = true; V["arrayValue"].append("a"); V["arrayValue"].append("b"); Json::Value tmp;
tmp["name"] = "zf"; tmp["age"] = 23; V["objectValue"] = tmp; cout << V << endl; return 0; }

輸出如下:

{
    "arrayValue" : [ "a", "b" ],
    "booleanValue" : true,
    "intValue" : -1,
    "nullValue" : null,
    "objectValue" : 
    {
        "age" : 23,
        "name"
: "zf" }, "realValue" : 3.140, "stringValue" : "Hello World", "uintValue" : 2 }

Writer

Json::FastWriter、Json::StyledWriter、Json::StyledStreamWriter
使用例項

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

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

輸出如下:

{"arrayValue":["a","b"],"booleanValue":true,"intValue":-1,"nullValue":null,"objectValue":{"age":23,"name":"zf"},"realValue":3.140,"stringValue":"Hello World","uintValue":2}

{
  "arrayValue" : [ "a", "b" ],
  "booleanValue" : true,
  "intValue" : -1,
  "nullValue" : null,
  "objectValue" : {
      "age" : 23,
      "name" : "zf"
  },
  "realValue" : 3.140,
  "stringValue" : "Hello World",
  "uintValue" : 2
}

Reader

用於將字串轉換為Jaon::Value物件

Json::Reader reader;
Json::Value object;

const char* json_string = "{\"name\" : \"zf\", \"age\" : 23}";
if (!reader.parse(json_string, object)) {
    cout << "Json parse error." << endl;
}

cout << object << endl;

輸出如下:

{
    "age" : 23,
    "name" : "zf"
}