From 146504d6357513fded0eaf4edc77e0c2a1ee1640 Mon Sep 17 00:00:00 2001 From: iwubcode Date: Tue, 19 Mar 2024 22:33:48 -0500 Subject: [PATCH] Common: add json utility functions 'ReadStringFromJson' and 'ReadBoolFromJson' to match 'ReadNumericFromJson' functionality for other data types, similarly support other data types for 'ToJsonArray' --- Source/Core/Common/JsonUtil.cpp | 20 ++++++++++++++++++++ Source/Core/Common/JsonUtil.h | 16 +++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/Source/Core/Common/JsonUtil.cpp b/Source/Core/Common/JsonUtil.cpp index 9ba23b6e1e..3e842c5c18 100644 --- a/Source/Core/Common/JsonUtil.cpp +++ b/Source/Core/Common/JsonUtil.cpp @@ -18,3 +18,23 @@ void FromJson(const picojson::object& obj, Common::Vec3& vec) vec.y = ReadNumericFromJson(obj, "y").value_or(0.0f); vec.z = ReadNumericFromJson(obj, "z").value_or(0.0f); } + +std::optional ReadStringFromJson(const picojson::object& obj, const std::string& key) +{ + const auto it = obj.find(key); + if (it == obj.end()) + return std::nullopt; + if (!it->second.is()) + return std::nullopt; + return it->second.to_str(); +} + +std::optional ReadBoolFromJson(const picojson::object& obj, const std::string& key) +{ + const auto it = obj.find(key); + if (it == obj.end()) + return std::nullopt; + if (!it->second.is()) + return std::nullopt; + return it->second.get(); +} diff --git a/Source/Core/Common/JsonUtil.h b/Source/Core/Common/JsonUtil.h index b508970099..eec836d507 100644 --- a/Source/Core/Common/JsonUtil.h +++ b/Source/Core/Common/JsonUtil.h @@ -5,6 +5,7 @@ #include #include +#include #include @@ -18,12 +19,21 @@ template picojson::array ToJsonArray(const Range& data) { + using RangeUnderlyingType = typename Range::value_type; picojson::array result; result.reserve(std::size(data)); for (const auto& value : data) { - result.emplace_back(static_cast(value)); + if constexpr (std::is_integral_v || + std::is_floating_point_v) + { + result.emplace_back(static_cast(value)); + } + else + { + result.emplace_back(value); + } } return result; @@ -40,5 +50,9 @@ std::optional ReadNumericFromJson(const picojson::object& obj, const std:: return MathUtil::SaturatingCast(it->second.get()); } +std::optional ReadStringFromJson(const picojson::object& obj, const std::string& key); + +std::optional ReadBoolFromJson(const picojson::object& obj, const std::string& key); + picojson::object ToJsonObject(const Common::Vec3& vec); void FromJson(const picojson::object& obj, Common::Vec3& vec);