gpt4 book ai didi

c++ - 如何从 Qt 中的 JSON 数据中检索整数值

转载 作者:搜寻专家 更新时间:2023-10-31 01:05:30 25 4
gpt4 key购买 nike

如何从 QJsonValue 对象中检索整数值?假设我有以下 JSON 数据:

    {
"res": 1,
"message": "Common error"
}

我需要从这些数据中提取“res”值,所以我尝试使用以下代码:

QJsonDocument d = QJsonDocument::fromJson(some_json_data.toUtf8());
QJsonObject root_object = d.object();
QJsonValue res = root_object.value("res");

但我发现 QJsonValue 类没有成员函数 toInt 或类似的东西(有 toDouble, toString,等等)。遇到这种情况怎么办?通过 QjsonValue 类提取整数值的最佳方法是什么?

最佳答案

(tl;dr:答案末尾的单行解决方案。)

首先是一种让您完全控制的综合方式。下面的代码假定 int 的范围足以容纳您的整数,但可以扩展以适用于 int64_t 的大部分范围(但最好测试边界情况以使其完全正确):

QJsonValue res = root_object.value("res");

int result = 0;
double tmp = res.toDouble();
if (tmp >= std::numeric_limits<int>::min() && // value is not too small
tmp <= std::numeric_limits<int>::max() && // value is not too big
std::floor(tmp) == tmp // value does not have decimals, if it's not ok
) {
result = std::floor(tmp); // let's be specific about rounding, if decimals are ok
} else {
// error handling if you are not fine with 0 as default value
}

使用 QVariant 的更短方法,作为示例,如果您只想让 Qt 执行它,也可以将结果转换为更大的整数类型。我不确定它如何处理对于 double 来说太大而无法准确处理的整数值,所以如果这很重要,请再次进行更好的测试。

QJsonValue res = root_object.value("res");

QVariant tmp = res.toVariant();

bool ok = false;
qlonglong result = tmp.toLongLong(&ok);

if (!ok) {
// error handling if you are not fine with 0 as default value
}

或与忽略错误的一行相同,根据需要更改整数类型:

qlonglong result = root_object.value("res").toVariant().toLongLong();

关于c++ - 如何从 Qt 中的 JSON 数据中检索整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22474654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com