c++ - 使用“现代 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;
}
我想检测该值是否超出预期范围。有可能以某种方式完成吗?
解决方案
做你想做的唯一方法是实际检索更大整数类型的值,然后检查该值是否在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::strtoull
or期间解析该数字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
),但您可以使用任何您想要的类型。
推荐阅读
- google-sheets - 按月份分组的数据透视表中的堆积条形图?
- reactjs - 在父组件的 onClick 上一次又一次地添加子组件,每次都使用新的道具到子组件
- verilog - 时钟域交叉信号和抖动要求
- email - 自定义域电子邮件不适用于 Heroku
- newrelic - Quarkus 原生容器中的 Newrelic 支持
- emacs - 将光标定位在 yasnippet 中的指定位置
- keras - ValueError:输入数组应具有与目标数组 LSTM Keras 相同数量的样本
- java - Java“空指针异常” - responseEntity.getBody().isNull()
- c++ - 字符串数组C ++中的字符识别不正确
- http - ?t=some-number 在图片网址末尾使用时是什么意思