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

使用nlohmann json库parse时报json.exception.type_error.302错误求助

问题根因
  1. [json.exception.type_error.302] 异常不会在json::parse阶段触发,parse仅会在JSON语法非法时报错,该异常是parse完成后,你对JSON对象执行数字类型取值操作时,对应字段实际为字符串类型导致的,你大概率是省略了parse后的取值代码,误判了异常触发时机。
  2. 你贴出的JSON样例本身没有类型问题,说明运行时实际拿到的mbuf.payload内容与样例不符,存在某个预期为数字的字段被添加了双引号转为字符串类型,常见出错字段为policy_type_id或threshold的赋值。

错误JSON示例:

{
  "policy_type_id": "20008", // 数字被包裹双引号,变为string类型
  "create_schema": {
    "properties": {
      "threshold": {
        "default": "0" // 同样属于错误格式
      }
    }
  }
}
解决方案
  • 优先修正上游JSON生成逻辑:打印mbuf.payload的实际运行值,定位类型错误的数字字段,修改上游逻辑输出数字时不加双引号,从根源解决问题。
  • 兼容异常场景(上游逻辑不可改时使用):取值时增加类型判断,兼容字符串格式的数字,示例代码如下:
// 通用数字取值兼容函数
template<typename T>
T get_num(const nlohmann::json& j) {
    if (j.is_string()) {
        if constexpr (std::is_same_v<T, int>) {
            return std::stoi(j.get<std::string>());
        } else if constexpr (std::is_same_v<T, double>) {
            return std::stod(j.get<std::string>());
        }
    }
    return j.get<T>();
}

// 调用示例
int policy_type_id = get_num<int>(payload["policy_type_id"]);
int threshold_default = get_num<int>(payload["create_schema"]["properties"]["threshold"]["default"]);
  • 新增调试定位逻辑:给所有JSON取值操作加异常捕获,快速定位出错字段:
try {
    // 你的JSON取值逻辑
} catch (const nlohmann::json::type_error& e) {
    std::cerr << "Type error: " << e.what() << std::endl;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:06:11