diff include/core/json.h @ 202:71832ffe425a

animia: re-add kvm fd source this is all being merged from my wildly out-of-date laptop. SORRY! in other news, I edited the CI file to install the wayland client as well, so the linux CI build might finally get wayland stuff.
author Paper <paper@paper.us.eu.org>
date Tue, 02 Jan 2024 06:05:06 -0500
parents bc1ae1810855
children 79a87a6dd39d
line wrap: on
line diff
--- a/include/core/json.h	Sun Nov 19 19:13:28 2023 -0500
+++ b/include/core/json.h	Tue Jan 02 06:05:06 2024 -0500
@@ -1,14 +1,57 @@
 #ifndef __core__json_h
 #define __core__json_h
 
-#include "json/json.h"
+#include "json/json.hpp"
+
+#include <optional>
+
+namespace nlohmann {
+
+template<typename T>
+void to_json(nlohmann::json& j, const std::optional<T>& v)
+{
+	if (v.has_value())
+		j = v.value();
+	else
+		j = nullptr;
+}
+
+template<typename T>
+void from_json(const nlohmann::json& j, std::optional<T>& v)
+{
+	return j.is_null() ? std::nullopt : j.get<T>();
+}
+
+} // namespace nlohmann
 
 namespace JSON {
 
-std::string GetString(nlohmann::json const& json, nlohmann::json::json_pointer const& ptr, std::string def = "");
-int GetInt(nlohmann::json const& json, nlohmann::json::json_pointer const& ptr, int def = 0);
-bool GetBoolean(nlohmann::json const& json, nlohmann::json::json_pointer const& ptr, bool def = false);
-double GetDouble(nlohmann::json const& json, nlohmann::json::json_pointer const& ptr, double def = 0);
+template<typename T = std::string>
+T GetString(const nlohmann::json& json, const nlohmann::json::json_pointer& ptr, T def) {
+	if (json.contains(ptr) && json[ptr].is_string())
+		return json[ptr].get<T>();
+	else
+		return def;
+}
+
+template<typename T = int>
+T GetNumber(const nlohmann::json& json, const nlohmann::json::json_pointer& ptr, T def = 0) {
+	if (json.contains(ptr) && json[ptr].is_number())
+		return json[ptr].get<T>();
+	else
+		return def;
+}
+
+template<typename T = std::vector<std::string>>
+T GetArray(const nlohmann::json& json, const nlohmann::json::json_pointer& ptr, T def = 0) {
+	if (json.contains(ptr) && json[ptr].is_array())
+		return json[ptr].get<T>();
+	else
+		return def;
+}
+
+nlohmann::json GetValue(const nlohmann::json& json, const nlohmann::json::json_pointer& ptr);
+bool GetBoolean(const nlohmann::json& json, const nlohmann::json::json_pointer& ptr, bool def = false);
 
 } // namespace JSON