JsonCpp的常见用法

本文主要介绍JsonCpp的常见用法。

1 概述

引用GitHub上对于JSON和JsonCpp的介绍,内容如下:

JSON is a lightweight data-interchange format. It can represent numbers, strings, ordered sequences of values, and collections of name/value pairs.

JsonCpp is a C++ library that allows manipulating JSON values, including serialization and deserialization to and from strings. It can also preserve existing comment in unserialization/serialization steps, making it a convenient format to store user input files.

2 常见用法

2.1 判断value为null

可以使用JsonCpp的isNull()函数,判断json的value是否为空。

isNull()函数信息如下:

bool Json::Value::isNull () const

示例代码(json_check_null.cpp)的内容如下:

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

using namespace std;

int main()
{
    Json::Value root;
    string strJsonMsg;

    // 字符串类型
    root["occupation"]  = "paladin";
    // 布尔类型
    root["valid"]       = true;
    // 数字类型
    root["role_id"]     = 1;

    string strBuffer = root["someone"].asString();;

    if (root["someone"].isNull())
    {
        cout << "someone is null!" << endl;
    }

    if (root["sometwo"].isNull())
    {
        cout << "sometwo is null!" << endl;
    }

    // 将json转换为string类型
    strJsonMsg = root.toStyledString();
    
    cout<< "strJsonMsg is: " << strJsonMsg << endl;

    return 0;
}

编译并执行上述代码,结果如下:

根据上面的执行结果,可知:

  • 使用isNull()函数可以判断json的value是否为null;
  • 对于json某个字段来说,只要是在代码中使用过,在封装json时,都会被封装到json内容中。比如本例中的root["someone"]和root["sometwo"],代码中并未对两者进行赋值,但是只要有使用过这两者,那么它们就会被封装到json内容中。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liitdar

赠人玫瑰,手有余香,君与吾共勉

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值