【问题标题】:Converting to data structure using from_json使用 from_json 转换为数据结构
【发布时间】: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&lt;Address&gt;() 正在尝试解析只有 "address" 属性的 outer 对象。您需要先获取"address" 对象。
  • @Someprogrammerdude 是的,这是错误的!谢谢!

标签: c++ json nlohmann-json


【解决方案1】:

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

    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());

【讨论】:

    猜你喜欢
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    相关资源
    最近更新 更多