Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

example code compile error #1562

Closed
dongguaWDY opened this issue Apr 9, 2019 · 2 comments
Closed

example code compile error #1562

dongguaWDY opened this issue Apr 9, 2019 · 2 comments
Labels
kind: bug solution: proposed fix a fix for the issue has been proposed and waits for confirmation state: stale the issue has not been updated in a while and will be closed automatically soon unless it is updated

Comments

@dongguaWDY
Copy link

dongguaWDY commented Apr 9, 2019

#include <nlohmann/json.hpp>

// for convenience
using json = nlohmann::json;
namespace ns {
// a simple struct to model a person
struct person {
std::string name;
std::string address;
int age;
};
}
// create a person
ns::person p {"Ned Flanders", "744 Evergreen Terrace", 60};

// conversion: person -> json
json j = p;

std::cout << j << std::endl;
// {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}

// conversion: json -> person
auto p2 = j.getns::person();

// that's it
assert(p == p2);

error: no viable conversion from 'person' to 'json' (aka 'basic_json<>') json j = p;

@nlohmann
Copy link
Owner

nlohmann commented Apr 9, 2019

You need to add the code described in https://github.com/nlohmann/json#basic-usage:

namespace ns {
    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);
    }
} // namespace ns

The conversions don't work without the from_json/to_json functions.

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label Apr 9, 2019
@stale
Copy link

stale bot commented May 9, 2019

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the state: stale the issue has not been updated in a while and will be closed automatically soon unless it is updated label May 9, 2019
@stale stale bot closed this as completed May 16, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: bug solution: proposed fix a fix for the issue has been proposed and waits for confirmation state: stale the issue has not been updated in a while and will be closed automatically soon unless it is updated
Projects
None yet
Development

No branches or pull requests

2 participants