diff --git a/Source/Core/Common/JsonUtil.cpp b/Source/Core/Common/JsonUtil.cpp index d16f37f4f3..3e842c5c18 100644 --- a/Source/Core/Common/JsonUtil.cpp +++ b/Source/Core/Common/JsonUtil.cpp @@ -14,7 +14,27 @@ picojson::object ToJsonObject(const Common::Vec3& vec) void FromJson(const picojson::object& obj, Common::Vec3& vec) { - vec.x = ReadNumericOrDefault(obj, "x"); - vec.y = ReadNumericOrDefault(obj, "y"); - vec.z = ReadNumericOrDefault(obj, "z"); + vec.x = ReadNumericFromJson(obj, "x").value_or(0.0f); + 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 cee52432ff..eec836d507 100644 --- a/Source/Core/Common/JsonUtil.h +++ b/Source/Core/Common/JsonUtil.h @@ -3,7 +3,9 @@ #pragma once +#include #include +#include #include @@ -17,28 +19,40 @@ 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; } template -Type ReadNumericOrDefault(const picojson::object& obj, const std::string& key, - Type default_value = Type{}) +std::optional ReadNumericFromJson(const picojson::object& obj, const std::string& key) { const auto it = obj.find(key); if (it == obj.end()) - return default_value; + return std::nullopt; if (!it->second.is()) - return default_value; + return std::nullopt; 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);