[英]rapidjson crashed when json value should be INT but send as string type
我有一个 C++ 代码,它使用 Rapidjson 解析传入的 json 消息。
接收到的 json 消息包含一个 key:value 对 ("userID": 100),其中 value 是一个整数。
但是,如果该值作为字符串“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 )
请注意,RapidJSON 不会自动在 JSON 类型之间转换值。 例如,如果值是字符串,则调用 GetInt() 是无效的。 在调试模式下,它将使断言失败。 在发布模式下,行为未定义。 在以下部分中,我们将讨论有关查询单个类型的详细信息。
如果您查看链接文档的“查询编号”部分中的表格,您可以找到一些成员函数,您可以在提取类型之前使用它来测试类型。 在您的情况下,您可能想尝试IsInt()
编辑:对于特定用例 IsUint/GetUint 可能更合适,如评论中所指出的
尝试这个:
{
...,
...,
"UserId" : "100" // note double quotes for 100
}
如果“UserId”的值是字符串,则使用GetString()
查询而不是GetInt()
来查询它以通过断言测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.