Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
However,
type x; x = json;
doesn't work, because that would require adding a new assignment operator for
type
.
I find myself needing to use expression (2) more often then expression (1). This can get quite annoying, especially if
type
is something complicated.
In a few cases, I defined
template <typename U>
void convert(const json& j, U& x) { x = j.get<U>(); }
But it would be nice if get
had an overload taking a reference as an argument, so that the following would be possible.
type x;
json.get(x);
Is there already a function that does that, that just has a different name? I couldn't find one in the documentation.
Edit: I've submitted an issue on GitHub.
Edit 2: An alternative to the get
function, T& get_to(T&)
, will be included in release 3.3.0.
–
It actually does work. The basic_json
type has a templated conversion operator which just calls get<T>()
for you. The following code compiles just fine:
#include <nlohmann/json.hpp>
using nlohmann::json;
namespace ns {
struct MyType {
int i;
void to_json(json& j, MyType m) {
j = json{{"i", m.i}};
void from_json(json const& j, MyType& m) {
m.i = j.at("i");
int main() {
json j{{"i", 42}};
ns::MyType type;
type = j;
–
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.