此代码打印-1
:
#include <iostream>
#include <nlohmann/json.hpp>
int main()
{
auto jsonText = "{ \"val\" : 4294967295 }";
auto json = nlohmann::json::parse(jsonText);
std::cout << json.at("val").get<int>() << std::endl;
}
我想检测该值超出预期范围。是否有可能以某种方式完成?
最佳答案
做你想做的唯一方法是实际检索更大整数类型的值,然后检查该值是否在 int
的范围内.
using integer_t = nlohmann::json::number_integer_t;
auto ivalue = json.at("val").get<integer_t>();
if (ivalue < std::numeric_limits<int>::min() || ivalue > std::numeric_limits<int>::max()) {
// Range error...
}
一些细节...
号码在调用 parse()
期间被解析使用 std::strtoull
或 std::strtoll
(取决于 -
符号的存在),并转换为 nlohmann::json::number_integer_t
( int64_t
1) 或 nlohmann::json::number_unsigned_t
(uint64_t
1)。
当您使用 get<int>
查询值时,唯一要做的就是从存储的 int64_t
中进行转换/uint64_t
值 int
, 因此此时无法检查范围。
此外,您无法检索原始“字符串”,因为仅存储了实际(无符号)整数值。
1 int64_t
和 uint64_t
是自 nlohmann::json
以来的默认类型实际上是 basic_json
的别名模板(很像 std::string
),但您可以使用任何您想要的类型。
关于c++ - 使用 "JSON for Modern C++"库检测整数不适合指定类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57823644/