C++工程,rapidjson字符串爲空或亂碼,rapidjson超長字符串,rapidjson超大數據json串包不住

1,rapidjson超長字符串,rapidjson超大數據,json包不住

1.1,如圖所示,json串不完全

在這裏插入圖片描述

1.2,代碼

	std::string r_string;
    
    rapidjson::Document document;
    document.SetObject();
    rapidjson::Document::AllocatorType& allocator = document.GetAllocator();

    document.AddMember("density_number", 234, allocator);

    rapidjson::Value arr(rapidjson::kArrayType);
    for(int i=0; i<4048; i++) {
        arr.PushBack(i, allocator);
    }
    document.AddMember("array", arr, allocator);


    rapidjson::StringBuffer stringbuf; 
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(stringbuf);
    writer.SetMaxDecimalPlaces(4);
    document.Accept(writer);
    r_string = stringbuf.GetString();

    LOG_IF(INFO, m_glog_valid) << "record_json_pointer string_size:"<< r_string.size() 
        <<"       r_string:"<< r_string;

1.3,原因分析

glog輸出長度有限,json串實際上是完整的

2,rapidjson字符串爲空或亂碼

2.1,如下圖所示rapidjson字符串爲空或亂碼

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

2.2,原因分析

使用rapidjson時出現以上問題,1.不是完整的內容,2.多次轉義\

bid.AddMember(“adm”, rapidjson::StringRef(html_snippet.c_str(),html_snippet.size()), allocator);

stringRef(html_snippet.c_str())一開始以爲可能可能是字符串結束標誌問題,這種方式會調動C的strlen去查找\0判斷字符串結束,而指定字符串長度的size後仍然會有\u00000的亂碼出現.

使用另一種方式,未出現此種問題:
Value str_val;
str_val.SetString(html_snippet.c_str(),html_snippet.length(),allocator);
bid.AddMember(“adm”, str_val, allocator);

等價的方式:ringRef(html_snippet.c_str(),Value().SetString(html_snippet.c_str(),allocator).Move(),allocator)

回去仔細查看手冊對比源碼,這兩種方式的差異是StringRef是引用轉移,也就是把指針指向了真正內容所在的內存區域。而第二種方式是值copy的方式,會分配內存把字符串複製一份副本。所以問題的根源是html_snippet 是臨時局部變量,在document對象序列成json string是html_snippet局部變量已被析構,故轉移的方式指向的內存區域是未知的,導致了\00000的出現。

2.多次轉義\是嵌套json 對象導致。

2.3,代碼

document_obj.AddMember("image_path",rapidjson::StringRef(image_path.c_str()), allocator);

2.4,解決

document_obj.AddMember("image_path",
                    rapidjson::Value().SetString(image_path.c_str(), 
                        allocator).Move(),allocator);

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章