1 #include <iostream> 2 #include <optional> 3 #include <nlohmann/json.hpp> 4 5 // partial specialization (see https://json.nlohmann.me/features/arbitrary_types/) 6 NLOHMANN_JSON_NAMESPACE_BEGIN 7 template <typename T> 8 struct adl_serializer<std::optional<T>> 9 { to_jsonadl_serializer10 static void to_json(json& j, const std::optional<T>& opt) 11 { 12 if (opt == std::nullopt) 13 { 14 j = nullptr; 15 } 16 else 17 { 18 j = *opt; 19 } 20 } 21 }; 22 NLOHMANN_JSON_NAMESPACE_END 23 main()24int main() 25 { 26 std::optional<int> o1 = 1; 27 std::optional<int> o2 = std::nullopt; 28 29 NLOHMANN_JSON_NAMESPACE::json j; 30 j.push_back(o1); 31 j.push_back(o2); 32 std::cout << j << std::endl; 33 } 34