Replies: 4 comments 5 replies
-
You do not need to write conversions for namespace nlohmann
{
template <typename T>
struct adl_serializer<std::shared_ptr<T>>
{
static void to_json(json& j, const std::shared_ptr<T>& opt)
{
if (opt)
{
j = *opt;
}
else
{
j = nullptr;
}
}
static void from_json(const json& j, std::shared_ptr<T>& opt)
{
if (j.is_null())
{
opt = nullptr;
}
else
{
opt.reset(new T(j.get<T>()));
}
}
};
} Complete example: #include <iostream>
#include "json.hpp"
using json = nlohmann::json;
namespace nlohmann
{
template <typename T>
struct adl_serializer<std::shared_ptr<T>>
{
static void to_json(json& j, const std::shared_ptr<T>& opt)
{
if (opt)
{
j = *opt;
}
else
{
j = nullptr;
}
}
static void from_json(const json& j, std::shared_ptr<T>& opt)
{
if (j.is_null())
{
opt = nullptr;
}
else
{
opt.reset(new T(j.get<T>()));
}
}
};
}
struct foo {
int i = 42;
};
void to_json(json& j, const foo& f)
{
j["i"] = f.i;
}
int main()
{
auto shared_foo = std::make_shared<foo>();
std::shared_ptr<foo> null_foo = nullptr;
json j_foo = shared_foo;
json j_null = null_foo;
std::cout << j_foo << '\n' << j_null << std::endl;
} |
Beta Was this translation helpful? Give feedback.
-
Was this supposed to work only for pure Lots of errors but in the end:
|
Beta Was this translation helpful? Give feedback.
-
Hmmm got it. Looks like it works if I use this shared_ptr serializer you suggested. However, there's an specific case where I need to do
and it's trying to use the
I need to use Do you have any idea on what's happening? |
Beta Was this translation helpful? Give feedback.
-
Looks like Output, if helpful:
|
Beta Was this translation helpful? Give feedback.
-
In order to parse
std::vector<std::shared_ptr<VPN>>
where VPN can be the subtypes
OpenVPN
and other types likeMicrosoftVPN
,CiscoVPN
, etc, I had to do the following:then, for each subtype, I implement the
to_json
andfrom_json
:As you can see, I got many problems, like
if (j.at("type") == "OPENVPN")
. I have to compare with the string literal instead of the enum before I create the instance ofVPN
with the subtypeOpenVPN
for example. I had multiple tries after a lot of segfaults to realize what I was doing.Apparently
std::vector<CustomObject>
works without me having to do anything except implementingfrom_json
andto_json
forCustomObject
. But ifCustomObject = std::shared_ptr<OtherCustomObject>
then I need to implementfrom_json
andto_json
forstd::shared_ptr<OtherCustomObject>
.Shouldn't or couldn't the library handle
std::vector<std::shared_ptr<CustomObject>>
on its own? Do anybody have a better solution?Beta Was this translation helpful? Give feedback.
All reactions