-
-
Notifications
You must be signed in to change notification settings - Fork 6.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support serialisation of unique_ptr<>
and shared_ptr<>
#975
Comments
I'm just a user, but I don't think having this library supporting automatic pointer dereference is a good idea. |
Because... |
I am also not sure whether such an implicit dereference under the hood is adding simplicity or rather surprise. In any case, the described behavior can be achieved without changing the library: #include "json.hpp"
#include <iostream>
using json = nlohmann::json;
namespace nlohmann {
template <typename T>
struct adl_serializer<std::unique_ptr<T>> {
static void to_json(json& j, const std::unique_ptr<T>& opt) {
if (opt.get()) {
j = *opt;
} else {
j = nullptr;
}
}
};
}
int main()
{
std::unique_ptr<int> a = std::make_unique<int>(1);
std::unique_ptr<int> b;
json j = {a, b};
std::cout << j << std::endl;
} (prints |
Can I close this issue? |
Yep, sorry for the delay - that looks excellent. Given that it is that easy to do without changing the library I wouldn't change it either. Though maybe add it to the Readme? |
There is already an example for |
Shouldn't at least |
For |
Because it's not been posted by anyone, here is a complete implementation that also includes #include "nlohmann/json.hpp"
#include <memory>
NLOHMANN_JSON_NAMESPACE_BEGIN
// Allows serializing and deserializing contents behind a std::unique_ptr.
// See also: https://github.com/nlohmann/json/issues/975
template <typename T> struct adl_serializer<std::unique_ptr<T>> {
template <typename BasicJsonType> static void to_json(BasicJsonType& json_value, const std::unique_ptr<T>& ptr)
{
if (ptr.get()) {
json_value = *ptr;
} else {
json_value = nullptr;
}
}
template <typename BasicJsonType> static void from_json(const BasicJsonType& json_value, std::unique_ptr<T>& ptr)
{
T inner_val = json_value.template get<T>();
ptr = std::make_unique<T>(std::move(inner_val));
}
};
NLOHMANN_JSON_NAMESPACE_END (The same approach works for |
If you try something like this:
It will fail with a template error (
get_json()
isn't defined forunique_ptr
). I can't see a good reason why that shouldn't work by default. I would expectnull
for null pointers and the actual value otherwise.The text was updated successfully, but these errors were encountered: