Search code examples
c++jsonpointersstructnlohmann-json

Nlohmann's json library, json array to a vector of structs with pointers inside the struct


I saw this post about converting a json array to a vector of structs. I have a struct named Foo:

typedef struct Foo {
  Foo* SubFoo;
} Foo;

and when I try to do this:

void from_json(const nlohmann::json& j, Foo& f) {
    j.at("SubFoo").get_to(f.SubFoo);
}

It gives me this error:

error: no matching function for call to 'nlohmann::basic_json<>::get_to(Foo*&) const'
 j.at("SubFoo").get_to(a.SubFoo);

So how can I get from json with a pointer to a value?


Solution

  • Just dereference the pointer:

    void from_json(const nlohmann::json& j, Foo& f) {
        j.at("SubFoo").get_to(*f.SubFoo);
    }
    

    Here's a demo.

    You'll have to ensure that you are not dereferencing an invalid pointer though.