I'm trying to write a json structure using rapidjson the sax way. Here's what I do:
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();
But the result is not what I'd expect, it's:
{
"userList": [
"userId",
20,
"productIdList",
[
1,
2
],
"userId",
21,
"productIdList",
[
1,
2
]
]
}
It looks like everything inside the first StartArray EndArray becomes an array element. What I'd like to obtain instead is:
{
"userList": [
{
"userId" : 20,
"productIdList" : [1, 2],
},
{
"userId" : 21,
"productIdList" : [1, 2]
}
]
}
Am I doing something wrong or what I want is not supported at all?
Before you call writer.Key("userId");
in the for loop, add writer.StartObject();
, and add writer.EndObject();
correspondingly. Here is an example:
#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;
}