Nlohmann 的 json 库,json 数组到结构向量,结构内部有指针

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

我看到 post 关于将 json 数组转换为结构向量。我有一个名为 Foo:

的结构
typedef struct Foo {
  Foo* SubFoo;
} Foo;

当我尝试这样做时:

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

它给我这个错误:

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

那么我怎样才能从 json 得到一个指向值的指针呢?

只需取消引用指针:

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

这里是 demo

尽管如此,您必须确保没有解除对无效指针的引用。