本文主要介绍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内容中。