问题
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