c++ - 使用 "JSON for Modern C++"库检测整数不适合指定类型?

标签 c++ json nlohmann-json

此代码打印-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::strtoullstd::strtoll (取决于 - 符号的存在),并转换为 nlohmann::json::number_integer_t ( int64_t 1) 或 nlohmann::json::number_unsigned_t (uint64_t 1)。

当您使用 get<int> 查询值时,唯一要做的就是从存储的 int64_t 中进行转换/uint64_tint , 因此此时无法检查范围。

此外,您无法检索原始“字符串”,因为仅存储了实际(无符号)整数值。

1 int64_tuint64_t是自 nlohmann::json 以来的默认类型实际上是 basic_json 的别名模板(很像 std::string ),但您可以使用任何您想要的类型。

关于c++ - 使用 "JSON for Modern C++"库检测整数不适合指定类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57823644/

相关文章:

c++ - 在 xcode 中编译和链接 OpenCV 3.0.0 时遇到问题

C++:处理许多配置变量的设计建议

c++ - auto stdMaxInt = std::max<int> 的类型推导失败;

c++ - 嵌套 for 循环 - 一维索引

javascript - 如何在 Google Apps 脚本中访问解析嵌套 JSON 中的对象

c# - 使用 Json.net 将大量数据流式传输为 JSON 格式

c++ - 如何使用nlohmann检查c++中嵌套json中是否存在 key

java - 如何解压缩 jsonlz4 Mozilla Firefox session 文件?

c++ - Nlohmann json 获取类型推导

C++,JSON,获取数组中的对象成员