-
I'm trying to deserialize unreliable data from a network endpoint. I can overload This following will print #include <cstdint>
#include <iostream>
#include <nlohmann/json.hpp>
#include <optional>
using json = nlohmann::json;
namespace nlohmann {
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 = {};
} else {
opt = j.get<T>();
}
}
};
}
struct packet {
std::optional<uint32_t> id;
};
packet receive(const json& data) {
packet pkt{};
pkt.id = data["id"].get<std::optional<uint32_t>>();
return pkt;
}
int main() {
std::string data = "{ \"id\": \"not a number\" }";
try {
receive(json::parse(data, nullptr, false));
} catch (std::exception& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
return 0;
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You could use |
Beta Was this translation helpful? Give feedback.
You could use
is_number()
ortype()
to check the type.