JsonCpp 用法简介

13 篇文章 0 订阅
2 篇文章 0 订阅

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"
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值