有没有办法用nlohmann_json lib序列化异构向量?

问题描述

嗨,堆栈溢出社区!

我正在一个项目上大量使用有趣的nlohmann_json库,看来我需要在特定的类上添加一个继承链接,这些对象可以同时序列化。

我尝试了在该库的github Issues页面上找到的其他建议,但无法使其正常工作。

这是我尝试过的伪代码:

#include <nlohmann/json.hpp>

#include <iostream>
#include <memory>
#include <vector>

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) {
                j = *opt.get();
            } else {
                j = nullptr;
            }
        }
    };
}

class Base {
    public:
        Base() = default;
        virtual ~Base() = default;
        virtual void foo() const { std::cout << "Base::foo()" << std::endl; }
};

class Obj : public Base
{
    public:
        Obj(int i) : _i(i) {}
        void foo() const override { std::cout << "Obj::foo()" << std::endl; }
        int _i = 0;
        friend std::ostream& operator<<(std::ostream& os,const Obj& o);
};

std::ostream& operator<<(std::ostream& os,const Base& o)
{
    os << "Base{} ";
    return os;
}

std::ostream& operator<<(std::ostream& os,const Obj& o)
{
    os << "Obj{"<< o._i <<"} ";
    return os;
}

void to_json(json& j,const Base& b)
{
    std::cout << "called to_json for Base" << std::endl;
}

void to_json(json& j,const Obj& o)
{
    std::cout << "called to_json for Obj" << std::endl;
}

int main()
{
    std::vector<std::unique_ptr<Base>> v;
    v.push_back(std::make_unique<Base>());
    v.push_back(std::make_unique<Obj>(5));
    v.push_back(std::make_unique<Base>());
    v.push_back(std::make_unique<Obj>(10));

    std::cout << v.size() << std::endl;

    json j = v;
}
// Results in :
// Program returned: 0
// 4
// called to_json for Base
// called to_json for Base
// called to_json for Base
// called to_json for Base

https://gcc.godbolt.org/z/dc8h8f

我知道adl_serializer在被调用时只会得到类型Base,但是我也看不出如何使他知道类型Obj的... >

有人看到我在这里丢失了吗?

在此先感谢您的建议和帮助!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)