I have the below program where I am trying to parse one json into a structure. See that I am the structure Address which I am trying to load from the json string.
However there is some exception.
#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!
}
What is going on wrong here? I see the below output.
> [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.