From 9e7a0bca31c2cf90eb310bb44167776325ab8ea5 Mon Sep 17 00:00:00 2001 From: Bernhard Kirchen Date: Sat, 13 Jul 2024 22:49:10 +0200 Subject: [PATCH] fix: handle numeric values disguised as strings in JSON closes #1104. --- src/Utils.cpp | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/Utils.cpp b/src/Utils.cpp index b7b42f567..5e26dfdf1 100644 --- a/src/Utils.cpp +++ b/src/Utils.cpp @@ -94,6 +94,24 @@ void Utils::removeAllFiles() } /* OpenDTU-OnBatter-specific utils go here: */ +template +std::optional getFromString(char const* val); + +template<> +std::optional getFromString(char const* val) +{ + float res = 0; + + try { + res = std::stof(val); + } + catch (std::invalid_argument const& e) { + return std::nullopt; + } + + return res; +} + template std::pair Utils::getJsonValueByPath(JsonDocument const& root, String const& path) { @@ -156,13 +174,24 @@ std::pair Utils::getJsonValueByPath(JsonDocument const& root, String return { T(), String(errBuffer) }; } - if (!value.is()) { + if (value.is()) { + return { value.as(), "" }; + } + + if (!value.is()) { snprintf(errBuffer, kErrBufferSize, "Value '%s' at JSON path '%s' is not " "of the expected type", value.as().c_str(), path.c_str()); return { T(), String(errBuffer) }; } - return { value.as(), "" }; + auto res = getFromString(value.as()); + if (!res.has_value()) { + snprintf(errBuffer, kErrBufferSize, "String '%s' at JSON path '%s' cannot " + "be converted to the expected type", value.as().c_str(), path.c_str()); + return { T(), String(errBuffer) }; + } + + return { *res, "" }; } template std::pair Utils::getJsonValueByPath(JsonDocument const& root, String const& path);