【发布时间】:2021-01-12 02:57:34
【问题描述】:
我已经定义了以下序列化程序堆栈:
namespace discordpp {
using Snowflake = uint64_t;
}
namespace nlohmann {
template <> struct adl_serializer<discordpp::Snowflake> {
static void to_json(json &j, const discordpp::Snowflake sf) {
j = std::to_string(sf);
}
static void from_json(const json &j, discordpp::Snowflake sf) {
std::istringstream(j.get<std::string>()) >> sf;
}
};
template <typename T> struct adl_serializer<std::shared_ptr<T>> {
static void from_json(json &j, std::shared_ptr<T> &ptr) {
if (j.is_null()) {
ptr == nullptr;
} else {
ptr = std::make_shared<T>(j.get<T>());
}
}
static void to_json(json &j, const std::shared_ptr<T> &ptr) {
if (ptr.get()) {
j = *ptr;
} else {
j = nullptr;
}
}
};
template <typename T> struct adl_serializer<std::shared_ptr<const T>> {
static void from_json(json &j, std::shared_ptr<const T> &ptr) {
if (j.is_null()) {
ptr == nullptr;
} else {
ptr = std::make_shared<const T>(j.get<T>());
}
}
static void to_json(json &j, const std::shared_ptr<const T> &ptr) {
if (ptr.get()) {
j = *ptr;
} else {
j = nullptr;
}
}
};
template <typename T> struct adl_serializer<std::optional<T>> {
static void to_json(json &j, const std::optional<T> &opt) {
if (opt.has_value()) {
j = nullptr;
} else {
j = *opt;
}
}
static void from_json(const json &j, std::optional<T> &opt) {
if (j.is_null()) {
opt = std::nullopt;
} else {
opt = j.get<T>();
}
}
};
}
我正在研究这样的事情:
class MessageIn : protected util::ObjectIn {
public:
...
opt<sptr<const Snowflake>> guild_id;
...
}
void from_json(const json &j, MessageIn *m) {
...
j["guild_id"].get<Snowflake>();
j["guild_id"].get<const Snowflake>();
j["guild_id"].get<sptr<const Snowflake>>();
m->guild_id = j["guild_id"].get<opt<sptr<const Snowflake>>>();
...
}
我的编译器在带有error: no matching function for call to ‘nlohmann::basic_json<>::get<discordpp::sptr<const long unsigned int> >() const’ 的j["guild_id"].get<sptr<const Snowflake>>(); 行上抛出错误。我错过了什么吗?
【问题讨论】:
-
出于某种原因,我得到了类似的错误,即使方法是静态的。您是否有机会使用适合您的“最终”adl_serializer 代码发布/编辑?
-
@IdanB 我不再这样做了,但我最终还是使用了这个:github.com/nlohmann/json/issues/1749#issuecomment-772996219
-
@IdanB 哦,是的,我想我开始遇到问题,Nlohmann 的 JSON 将每个整数转换为
std::string我决定结合使用这种方法:github.com/DiscordPP/discordpp/blob/… 并手动来回转换它来自字符串:github.com/…
标签: c++ parsing templates shared-ptr nlohmann-json