当 json 值应为 INT 但作为字符串类型发送时,rapidjson 崩溃

rapidjson crashed when json value should be INT but send as string type

我有一个 C++ 代码,它使用快速 json 解析传入的 json 消息。

收到的json消息包含一对key:value("userID":100),其中值为整数。

但是,如果该值作为字符串“100”发送,rapidjson 会导致整个程序崩溃并出现以下错误:

Invalid response: { "error": "ERR_RATE_LIMIT"}
trading: ../../include/rapidjson/document.h:1737: int rapidjson::GenericValue<Encoding, Allocator>::GetInt() const [with Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>]: Assertion `data_.f.flags & kIntFlag' failed.
/home/ray/dev/trading_execution/src/trading/trading.run.sh: line 39:  2518 Aborted                 (core dumped) ./trading 1234

我希望 rapidjson 可以比让程序崩溃更温和地处理这个问题。

对如何处理这种情况有什么建议吗?例如,有没有更好的方法来处理错误?

Json 留言:

{
   "ctRequestId":   "cfa5511f-8c1a-492b-b81a-1462d03bbe99",
    "requestType":  "generic",  
    "userID":       100,                        
}

代码:

    userID          = getJSONInt(document,      "userID");      

    int getJSONInt(rapidjson::Document& document, const char* memberName)
    {
    int memberValue;

    try
    {
        if (document.HasMember(memberName))
        memberValue = document[memberName].GetInt();
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << '\n';
    }

    return memberValue;
}

不是rapidjson专家,但根据文档(http://rapidjson.org/md_doc_tutorial.html)

Note that, RapidJSON does not automatically convert values between JSON types. If a value is a string, it is invalid to call GetInt(), for example. In debug mode it will fail an assertion. In release mode, the behavior is undefined. In the following sections we discuss details about querying individual types.

如果您查看链接文档 "Querying Number" 部分中的 table,您可以找到一些成员函数,您可以在提取它之前使用它来测试类型。在您的情况下,您可能想尝试 IsInt()

编辑:对于特定用例,IsUint/GetUint 可能更合适,如评论中指出的那样

试试这个:

{
...,
...,
"UserId" : "100"  // note double quotes for 100
}

如果“UserId”的值为字符串,则使用GetString()查询而不是GetInt()查询以通过断言测试。