You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何QJsonDocument::fromJson无法解析JSON简单值?

QJsonDocument解析单个JSON简单值触发IllegalValue错误的原因

你遇到的问题核心在于QJsonDocument::fromJson要求输入的是完整的JSON文档,而JSON规范定义的“文档”顶层必须是对象({})或者数组([])——单个布尔值、null、数字或字符串并不符合这个文档结构要求,因此会被判定为非法值,触发QJsonParseError::IllegalValue错误。

要解决这个问题,只需把单个简单值包裹在数组或对象中再解析即可:

方法1:用数组包裹单个值

QJsonParseError err;
auto doc = QJsonDocument::fromJson("[true]", err);
if (!doc.isNull()) {
    QJsonValue value = doc.array().first();
    qInfo() << value.toBool(); // 输出 true
} else {
    qInfo() << err.errorString();
}

方法2:用对象包裹单个值

QJsonParseError err;
auto doc = QJsonDocument::fromJson("{\"value\": true}", err);
if (!doc.isNull()) {
    QJsonValue value = doc.object()["value"];
    qInfo() << value.toBool(); // 输出 true
} else {
    qInfo() << err.errorString();
}

通过这种方式就能正常解析出你需要的单个简单值。

内容的提问来源于stack exchange,提问作者Bogudan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 17:44:52