版权声明:本文为博主原创文章,商业转载请联系作者获得授权,非商业转载请注明出处。 https://blog.csdn.net/liitdar/article/details/82021279
本文主要介绍使用 jsoncpp 时常用的操作。
1 判断value为null
我们可以使用 jsoncpp 的 isNull() 函数,判断 json 的 value 是否为空。函数如下:
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 中。