【发布时间】:2021-03-05 06:31:05
【问题描述】:
我有下面的程序,我试图将一个 json 解析成一个结构。 看到我是我试图从 json 字符串加载的结构地址。
但是有一些例外。
#include <string>
#include <nlohmann/json.hpp>
using nlohmann::json;
struct Address
{
std::string houseNo;
std::string street;
std::string city;
std::string postalCode;
std::string country;
};
void from_json(const json& j, Address& address)
{
j.at("house").get_to(address.houseNo);
j.at("street").get_to(address.street);
j.at("street").get_to(address.street);
j.at("city").get_to(address.city);
j.at("postalCode").get_to(address.postalCode);
j.at("country").get_to(address.country);
}
int main()
{
std::string str =
"{\
\"address\": {\
\"city\": \"XYZ\",\
\"country\": \"country\",\
\"house\": \"123\",\
\"postalCode\": \"123456\",\
\"street\": \"St. ABC\"\
}\
}";
json j = json::parse(str);
printf("[UT_JsonTest] Input json string : \n %s \n", j.dump(4).c_str());
auto a = j.get<Address>(); //exception here!
}
这里出了什么问题? 我看到下面的输出。
> [UT_JsonTest] Input json string : {
> "address": {
> "city": "XYZ",
> "country": "country",
> "house": "123",
> "postalCode": "123456",
> "street": "St. ABC"
> } } unknown file: Failure C++ exception with description "[json.exception.out_of_range.403] key 'house' not found" thrown in
> the test body.
【问题讨论】:
-
我的猜测是
j.get<Address>()正在尝试解析只有"address"属性的 outer 对象。您需要先获取"address"对象。 -
@Someprogrammerdude 是的,这是错误的!谢谢!
标签: c++ json nlohmann-json