首页 > 解决方案 > 使用“现代 C++ 的 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;
}

我想检测该值是否超出预期范围。有可能以某种方式完成吗?

标签: c++jsonnlohmann-json

解决方案


做你想做的唯一方法是实际检索更大整数类型的值,然后检查该值是否在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() 在调用using std::strtoullor期间解析该数字std::strtoll(取决于-符号的存在),并转换为nlohmann::json::number_integer_t( int64_t1 ) 或nlohmann::json::number_unsigned_t( uint64_t1 )。

当您使用 查询值时get<int>,唯一要做的就是将存储的int64_t/uint64_t值强制转换为int,因此此时无法检查范围。

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

1 int64_t并且uint64_t是默认类型,因为nlohmann::json它实际上是basic_json模板的别名(很像std::string),但您可以使用任何您想要的类型。


推荐阅读