微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C ++ RapidJSON获取存在数组的附加值

如何解决C ++ RapidJSON获取存在数组的附加值

我试图创建一个将为Json数组添加值的类。我试图这样做:

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);

}

但是我有一个错误

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.

我该如何正确做?

解决方法

看看rapidjson/document.h:1218,这似乎是您将[]运算符与不存在的成员(可能在您访问JsonObj["array"]的位置)一起使用时出错的原因。 / p>

如果我先使用MemberFind来查找该成员,则对我来说效果很好:

rapidjson::Document::MemberIterator existingArray = JsonObj.FindMember("array");
if (existingArray != JsonObj.MemberEnd() && !existingArray->value.IsNull())
    array = existingArray->value;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。