使用 from_json 转换为数据结构

问题描述

我有下面的程序,我试图将一个 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.

enter image description here

解决方法

感谢您的快速提示! 在解析它之前,我必须选择“地址”值!

    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 address = j.at("address").get<Address>();

    printf("[UT_JsonTest] address.city = %s\n",address.city.c_str());