Skip to content

how to convert json to object with "new" keyword #2565

Answered by nlohmann
Hanbunhanabi asked this question in Q&A
Discussion options

You must be logged in to vote

This works:

#include <iostream>
#include "json.hpp"

using json = nlohmann::json;

namespace ns {
struct person {
    std::string name;
    std::string address;
    int age;
};

void to_json(json& j, const person& p) {
    j = json{{"name", p.name}, {"address", p.address}, {"age", p.age}};
}

void from_json(const json& j, person& p) {
    j.at("name").get_to(p.name);
    j.at("address").get_to(p.address);
    j.at("age").get_to(p.age);
}
}

int main()
{
    json j = R"({"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"})"_json;
    auto* p = new ns::person(j);
    std::cout << p->name << ", " << p->address << ", " << p->age << std::endl;
}

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@nlohmann
Comment options

@Hanbunhanabi
Comment options

Answer selected by nlohmann
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants