JsonCpp如何判断是否有某个KEY

JsonCpp如何判断是否有某个KEY,使用json[“key”]和isXXX的函数即可。
如果json中没有key键,则会创建一个空成员或者返回一个空成员。

// Access an object value by name, create a null member if it does not exist.
Value &operator[]( const char *key );
// Access an object value by name, returns null if there is no member with that name.
const Value &operator[]( const char *key ) const;
// Access an object value by name, create a null member if it does not exist.
Value &operator[]( const std::string &key );
// Access an object value by name, returns null if there is no member with that name.
const Value &operator[]( const std::string &key ) const;

bool isNull() const;
bool isBool() const;
bool isInt() const;
bool isUInt() const;
bool isIntegral() const;
bool isDouble() const;
bool isNumeric() const;
bool isString() const;
bool isArray() const;
bool isObject() const;

例如要判断Json数据中是否有{“status”:”1”}数据,则可以

if(json["staus"].isString()){
    string temp = json["staus"].asCString();
}

如果Json中没有status键就不会提取该数据。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
要使用jsoncpp读取JSON文件中的某个属性,可以使用Json::Value对象和Json::Reader对象。首先,你需要使用Json::Reader对象将JSON文件解析为Json::Value对象。然后,你可以使用Json::Value对象的索引或成员函数来获取所需的属性值。 下面是一个示例代码,演示了如何使用jsoncpp读取JSON文件中的某个属性: ```cpp #include <iostream> #include <fstream> #include "json/json.h" int main() { // 读取JSON文件 std::ifstream file("bookinfo.json"); Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse(file, root); if (!parsingSuccessful) { std::cout << "解析JSON文件失败,请检查文件格式或路径。" << std::endl; return 1; } // 获取属性值 std::string title = root["title"].asString(); int year = root["year"].asInt(); std::string author = root["author"].asString(); // 输出属性值 std::cout << "书名: " << title << std::endl; std::cout << "出版年份: " << year << std::endl; std::cout << "作者: " << author << std::endl; return 0; } ``` 在这个示例中,我们首先使用`std::ifstream`打开`bookinfo.json`文件,并将其读取到`std::string`中。然后,我们使用`Json::Reader`对象的`parse`函数将文件内容解析为`Json::Value`对象。如果解析成功,我们就可以使用`Json::Value`对象的索引或成员函数来获取所需的属性值。 在这个示例中,我们通过`root["title"].asString()`获取了JSON文件中的`title`属性的字符串值,通过`root["year"].asInt()`获取了`year`属性的整数值,通过`root["author"].asString()`获取了`author`属性的字符串值。最后,我们将这些属性值输出到控制台。 请注意,你需要在编译时链接jsoncpp库,并在代码中包含头文件"json/json.h"。 希望这个示例可以帮助你使用jsoncpp读取JSON文件中的某个属性。如果有任何问题,请随时提问。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值