IsObject assert failed
使用未正确解析的JSON文件会报出如下错误
fail_parse_not_a_json: /usr/local/include/rapidjson/document.h:1359: rapidjson::GenericValue<Encoding, Allocator>::MemberIterator rapidjson::GenericValue<Encoding, Allocator>::FindMember(const rapidjson::GenericValue<Encoding, SourceAllocator>&) [with SourceAllocator = rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>; Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>; rapidjson::GenericValue<Encoding, Allocator>::MemberIterator = rapidjson::GenericMemberIterator<false, rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator> >]: Assertion `IsObject()' failed.
rapidjson检测是否是一个正确的JSON输入
参照官方文档建议使用 HasParseError 来检测parse的错误
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
using namespace rapidjson;
int main() {
// 1. 把 JSON 解析至 DOM。这里不是一个有效地JSON字符串
const char* json = "{\"msg\": {\"seq\":8E-J3 }}";
Document d;
if(d.Parse(json).HasParseError()){
std::cout << "parse error found!" << std::endl;
}
if(!d.IsObject()){
std::cout << "not a correct json format!" << std::endl;
return 0;
}
// 2. 利用 DOM 作出修改。
Value& s = d["stars"];
s.SetInt(s.GetInt() + 1);
// 3. 把 DOM 转换(stringify)成 JSON。
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
// Output {"project":"rapidjson","stars":11}
std::cout << buffer.GetString() << std::endl;
return 0;
}
输出是
feiyu@fly2rain:~/dev/repo/repo_for_test/build$ ./fail_parse_not_a_json
parse error found!
not a correct json format!
引用:
rapidjson中文文档