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