如何使用rapidjson更新数组?

时间:2016-01-12 16:09:06

标签: c++ rapidjson

我用rapidjson做一些事情,我想为我刚创建的数组添加值

#include <iostream>
#include "rapidjson/document.h"
using namespace std ;

int main() {


    char json[1024];
    rapidjson::Document document ;
    document.Parse<0>(json);
    if (!document.IsObject()) {
            document.SetObject();
    }
    assert(document.IsObject());
    rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
    // adding member (int)
    document.AddMember("mohammed",25,allocator);
    assert(document.HasMember("mohammed"));
    cout << document["mohammed"].GetInt() << endl ;

    // adding member (array)
    rapidjson::Value array(rapidjson::kArrayType);
    array.PushBack(5,allocator);
    array.PushBack(6,allocator);
    cout << array[0u].GetInt() << endl ;
    cout << array[1].GetInt() << endl ;
    document.AddMember("array",array,allocator);
    assert(document.HasMember("array"));
    assert(document["array"].IsArray());
    // here the following line give me an error 
    array.PushBack(7,allocator);




}

错误是

json: rapidjson/document.h:397: rapidjson::GenericValue<Encoding, Allocator>& rapidjson::GenericValue<Encoding, Allocator>::PushBack(rapidjson::GenericValue<Encoding, Allocator>&, Allocator&) [with Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>]: Assertion `IsArray()' failed.

中止(核心倾销)

有人可以解释什么问题?发生了什么我对此有点新鲜,谢谢。

1 个答案:

答案 0 :(得分:3)

执行array.PushBack(...)时,array已经移动document,并变为空值类型(array.IsNull() == true)。所以你不能PushBack为空值。

document["array"].PushBack(7,allocator)将有效。