如何从Json获得价值

How to get value from Json

本文关键字:Json      更新时间:2023-10-16

我需要从一个有toJson()的Json AdSpot中获取值(String或int),我需要通过键"ext"(它也是一个Json)检索字段,然后通过键"isBanner"从ext.的Json值中检索字段

这是Json AdSpot:

AdSpot(OpenRTB::Impression && imp)
    : OpenRTB::Impression(std::move(imp))
{
}
void fromJson(const Json::Value & val);
Json::Value toJson() const;

我尝试使用get,但不知道该为默认值传递什么参数。

您将从jsoncpp文档中找到答案
从Json::Value中,您可以使用将其作为字符串获取

std::string asString()const

或使用作为整数

Int asInt()常量

然后,您的问题中的JSON导航可以使用:

Json::Value extValue = value["ext"];
Json::Value isBannerValue = extValue["isBanner"];
std::string isBanner = isBannerValue.asString();

如果不能强制转换,则会引发异常。