I tried to create a class which will add a value to a Json array. I tried to do it like this:
void functions::Json::SetArray(rapidjson::Document &JsonObj, std::string ArrayName, std::string value)
{
if (!JsonObj.IsObject())
JsonObj.SetObject();
rapidjson::Document::AllocatorType& alloc = JsonObj.GetAllocator();
rapidjson::Value KeyPart;
KeyPart.SetString(ArrayName.c_str(), alloc);
rapidjson::Value ValuePart;
ValuePart.SetString(value.c_str(), alloc);
rapidjson::Value array(rapidjson::kArrayType);
if (!JsonObj["array"].IsNull())
array = JsonObj["array"];
array.PushBack(ValuePart, alloc);
JsonObj.AddMember(KeyPart, array, alloc);
}
But I have an error:
rapidjson/document.h:1218: rapidjson::GenericValue<Encoding,
Allocator>& rapidjson::GenericValue<Encoding,
Allocator>::operator[](const rapidjson::GenericValue<Encoding,
SourceAllocator>&) [with SourceAllocator =
rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>; Encoding =
rapidjson::UTF8<>; Allocator =
rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>]: Assertion
`false' failed.
How do I correctly do it?
Taking a look at rapidjson/document.h:1218
, this appears to be how it errors when you use the []
operator with a member that doesn't exist, probably where you access JsonObj["array"]
.
If I use MemberFind
to look up the member first, it works fine for me:
rapidjson::Document::MemberIterator existingArray = JsonObj.FindMember("array");
if (existingArray != JsonObj.MemberEnd() && !existingArray->value.IsNull())
array = existingArray->value;