我有一個簡單的用例,我希望序列化和傳輸 0 到 256 之間的整數向量。我推測最節省空間的方法是將向量序列化為序列化字串,其中第 n 個字符具有相當于相應向量的第 n 個元素的 ASCII 碼。為此,我撰寫了以下兩個函式:
std::string SerializeToBytes(const std::vector<int> &frag)
{
std::vector<unsigned char> res;
res.reserve(frag.size());
for(int val : frag) {
res.push_back((char) val);
}
return std::string(res.begin(), res.end());
}
std::vector<int> ParseFromBytes(const std::string &serialized_frag)
{
std::vector<int> res;
res.reserve(serialized_frag.length());
for(unsigned char c : serialized_frag) {
res.push_back(c);
}
return res;
}
但是,在使用 JsonCpp 發送此資料時,我遇到了問題。下面的最小可重現示例表明該問題并非源于上述方法,而是僅在Json::Value序列化并隨后決議a 時出現。這會導致序列化字串中的某些編碼資料丟失。
#include <cassert>
#include <json/json.h>
int main() {
std::vector frag = { 230 };
std::string serialized = SerializeToBytes(frag);
// Will pass, indicating that the SerializeToBytes and ParseFromBytes functions are not the issue.
assert(frag == ParseFromBytes(serialized));
Json::Value val;
val["STR"] = serialized;
// Will pass, showing that the issue does not appear until JSON is serialized and then parsed.
assert(frag == ParseFromBytes(val["STR"].asString()));
Json::StreamWriterBuilder builder;
builder["indentation"] = "";
std::string serialized_json = Json::writeString(builder, val);
// Will be serialized to "{\"STR\":\"\\ufffd\"}".
Json::Value reconstructed_json;
Json::Reader reader;
reader.parse(serialized_json, reconstructed_json);
// Will produce { 239, 191, 189 }, rather than { 230 }, as it should.
std::vector<int> frag_from_json = ParseFromBytes(reconstructed_json["STR"].asString());
// Will fail, showing that the issue stems from the serialize/parsing process.
assert(frag == frag_from_json);
return 0;
}
此問題的原因是什么,我該如何解決?謝謝你的盡心幫助。
uj5u.com熱心網友回復:
Jsoncpp類值
此類是一個可區分的聯合包裝器,可以表示:
- ...
- UTF-8 字串
- ...
{ 230 }是無效的 UTF-8 字串。因此,Json::writeString(builder, val)對正確結果的進一步期望 是非法的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/396142.html
