gpt4 book ai didi

c++ - 用 rapidjson "SAX"方式写嵌套数组

转载 作者:行者123 更新时间:2023-11-30 05:42:10 29 4
gpt4 key购买 nike

我正在尝试以 sax 方式使用 rapidjson 编写 json 结构。这是我的做法:

  StringBuffer sb;
PrettyWriter<StringBuffer> writer(sb);
writer.StartObject();

writer.Key("user");
writer.StartArray();

OperatorAcPtrList::iterator xIt;
for (xIt = userList.begin(); xIt != userList.end(); xIt++)
{
writer.Key("userId");
writer.Uint((*xIt)->id);

writer.Key("productIdList");
writer.StartArray();

ProductIdList::iterator xPrdIdIt;
for (xPrdIdIt = ((*xIt)->productList).begin();
xPrdIdIt != ((*xIt)->productList).end(); xPrdIdIt++)
{
writer.Uint(*xPrdIdIt);
}
writer.EndArray();
}
writer.EndArray();
writer.EndObject();

但结果不是我所期望的,它是:

{
"userList": [
"userId",
20,
"productIdList",
[
1,
2
],
"userId",
21,
"productIdList",
[
1,
2
]
]
}

看起来第一个 StartArray EndArray 中的所有内容都变成了数组元素。我想获得的是:

{
"userList": [
{
"userId" : 20,
"productIdList" : [1, 2],
},
{
"userId" : 21,
"productIdList" : [1, 2]
}
]
}

是我做错了什么还是根本不支持我想要的?

最佳答案

在 for 循环中调用 writer.Key("userId"); 之前,添加 writer.StartObject();,并添加 writer.EndObject (); 对应。这是一个例子:

#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>

using namespace rapidjson;
using namespace std;

int main() {
StringBuffer s;
Writer<StringBuffer> writer(s);
writer.StartObject();

writer.Key("userList");
writer.StartArray();

writer.StartObject();
writer.Key("userId");
writer.Uint(20);
writer.Key("productIdList");
writer.StartArray();
for (unsigned i = 1; i < 3; i++)
writer.Uint(i);
writer.EndArray();
writer.EndObject();

writer.StartObject();
writer.Key("userId");
writer.Uint(21);
writer.Key("productIdList");
writer.StartArray();
for (unsigned i = 1; i < 3; i++)
writer.Uint(i);
writer.EndArray();
writer.EndObject();

writer.EndArray();
writer.EndObject();
cout << s.GetString() << endl;
}

关于c++ - 用 rapidjson "SAX"方式写嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30778624/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com