简体   繁体   English

Nlohmann 的 json 库,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.我看到这篇关于将 json 数组转换为结构向量的帖子。 I have a struct named Foo :我有一个名为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?那么我怎样才能从 json 获得一个指向值的指针呢?

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.您必须确保您没有取消引用无效指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM