如何使用Rapidjason解析根目录中的数组 [英] How to parse array in root with rapidjason

查看:173
本文介绍了如何使用Rapidjason解析根目录中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码.

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.

我发现的一种方法是使用writer,它接受stringBuffer.它给了我返回数组元素的嵌套字符串.

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:对于具有易用接口的c ++,有没有更好的jason解析器?

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

推荐答案

您,因为程序员应该知道您要序列化或反序列化的JSON字符串的格式.在这种情况下,您似乎正在考虑将字符串值作为整数.

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.

现在,要解决此问题,您可以将它们视为字符串,然后使用标准C ++实用程序将这些字符串值转换为整数,或者可以更新JSON字符串以包含整数.

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.

第一种方法(尽管没有以最好的方式完成对int的转换)

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";
}

第二种方法:

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";
}

这篇关于如何使用Rapidjason解析根目录中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆