如何使用 rapidjson 更新数组?

how to update an array using 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.

已中止(核心已转储)

谁能解释一下这是什么问题?发生了什么事我对此有点陌生,谢谢。

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

document["array"].PushBack(7,allocator) 可以。