【发布时间】:2017-06-28 17:07:18
【问题描述】:
我在 C++ 中使用 nlohmann::json 库对 JSON 对象进行 CBOR 序列化,我的用例涉及读取 c# 中的 cbor 字节字符串输出。我注意到,当使用 nlohmann::json 库将 json 对象转储到 C++ 中的字符串时,json 字符串值(即 case value_t::string)被转义(调用了 escape_string),没有这样的调用当 json 值是 CBOR 方法中的字符串值时生成。
我正在阅读 CBOR CRF 7049,在序列化为 CBOR 时似乎不需要转义字符串。 nlohmann::json 库中的行为是一致的:字符串在序列化时不转义,反序列化时也不例外。 但似乎 Newtonsoft.Json(C# 库)期望这一点。这是一个有效的期望吗?还是我在这个过程中做错了什么?
C++ 方面:
nlohmann::json json_doc;
json_doc["characters"] = nlohmann::json::array();
for (int i = 0; i < characters.size(); i++) {
json_doc["characters"][i]["name"] = (characters[i] != nullptr) ? characters[i]->name() : "";
}
std::vector<uint8_t> cbor = nlohmann::json::to_cbor(json_doc);
output->assign((char*)&cbor[0], cbor.size());
C# 方面。 cbor_bytes 是 cbor 字节串(c++ 输出向量)
CBORObject cbor = CBORObject.DecodeFromBytes(cbor_bytes);
output = cbor.ToString();
到那时,这样的输出字符串,格式错误:
{"characters": [{"name": "Clara Oswald"}, {"name": "Kensi Blye"}, {"name": "Temperance "Bones" Brennan"}]}
显然不能解析:
JObject output_obj = JObject.Parse(output);
【问题讨论】:
标签: c# json serialization json.net cbor