使用rapidjson编写嵌套数组" SAX"办法

时间:2015-06-11 10:45:29

标签: c++ rapidjson

我试图用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]
        }
    ]
}

我做错了什么或者我想要什么都不受支持?

1 个答案:

答案 0 :(得分:1)

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