How to parse array in root with rapidjason

扶醉桌前 提交于 2019-12-11 07:24:52

问题


I have follwing code.

Document d;
const char* json = "[{\"k1\":\"1\"}, {\"k1\":\"2\"}]";
d.Parse(json);
for (SizeType i = 0; i < d.Size(); i++) {
    cout << d[i]["k1"].GetInt() << "\n";
}

I get below error when I run this:

rapidjson/include/rapidjson/document.h:1700: int rapidjson::GenericValue<Encoding, Allocator>::GetInt() const [with Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>]: Assertion `data_.f.flags & kIntFlag' failed.

One way I figured out is using writer which accepts a stringBuffer. It gives me back the nested string of array element.

 rapidjson::StringBuffer sb;
 rapidjson::Writer<rapidjson::StringBuffer> writer1( sb );
 d[0].Accept( writer1 );
 std::cout << sb.GetString() << std::endl;

The output of above alternative is:

{"k1":"1"}

I can feed back above string output to parse again. Is there a way to parse this directly?

PS: Is there any better jason parser for c++ with easy interface?


回答1:


You, as the programmer should be aware of the format of the JSON string you are serializing or deserializing. It seems like, in this case, you are considering string values to be integers.

Now, to fix this, you can either treat them as strings and then convert those string values to integers using standard C++ utilities, or you can update your JSON string to contain integers.

The first approach (although the conversion to int is not done in the nicest way possible):

Document d;
const char* json = "[{\"k1\":1}, {\"k1\":2}]";
d.Parse(json);
for (SizeType i = 0; i < d.Size(); i++) {
    int d;
    sscanf(d[i]["k1"].GetString(), "%d", &d);
    cout << d << "\n";
}

The second approach:

Document d;
const char* json = "[{\"k1\":1}, {\"k1\":2}]";
d.Parse(json);
for (SizeType i = 0; i < d.Size(); i++) {
    cout << d[i]["k1"].GetInt() << "\n";
}


来源:https://stackoverflow.com/questions/46617782/how-to-parse-array-in-root-with-rapidjason

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!