不要像使用 JSON 库一样使用属性树。它有众所周知的局限性:https://www.boost.org/doc/libs/1_75_0/doc/html/property_tree/parsers.html#property_tree.parsers.json_parser
特别注意数组的限制。
接下来,你没有写一个数组开始,而是写一个字符串。但由于它是二进制数据,它可能是一个有效的 JSON 字符串,这可能是错误的来源。
另外,您可能不需要再次复制整个 JSON 以将其放入缓冲区。相反,boost::asio::buffer(resultString) 将起作用(只要您确保 resultString 的生命周期足够,就像 buffer_ 一样)。
稍微测试一下就表明write_json 可以正确转义字符:
Live On Compiler Explorer
#define BOOST_BIND_GLOBAL_PLACEHOLDERS
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
using namespace std::string_literals;
struct Im { std::array<std::uint64_t, 10> bits; };
int main()
{
auto im = std::make_unique<Im>(
Im { 0b0010'1100'1010'0010'0111'1100'0010 });
std::string_view bitmsg(
reinterpret_cast<char const*>(&im->bits),
sizeof(im->bits));
auto processResultJson = "some binary data: \0 \x10 \xef αβγδ\n"s;
processResultJson += bitmsg;
boost::property_tree::ptree docData;
docData.put("Image1", processResultJson);
std::ostringstream oss;
boost::property_tree::json_parser::write_json(oss, docData);
std::cout << oss.str();
}
打印
{ "Image1": "some binary data: \u0000 \u0010 αβγδ\nu0002\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000" }
Json lint 将其报告为有效的 JSON(物有所值)
但是,请考虑通过以下方式加倍确定
- 使用 base64 编码对二进制数据进行编码
- 使用 Boost JSON 或其他合适的 JSON 库
使用 Boost JSON 演示
1.75.0 引入了适当的 JSON 库。让我们庆祝一下吧。
直接翻译为:https://godbolt.org/z/es9jGc
json::object docData;
docData["Image1"] = processResultJson;
std::string resultString = json::serialize(docData);
不过,您现在可以轻松地使用强类型的正确数组:https://godbolt.org/z/K9c6bc
json::object docData;
docData["Image1"] = json::array(im->bits.begin(), im->bits.end());
打印
{"Image1":[46802882,0,0,0,0,0,0,0,0,0]}
实际上,您也可以使用value_from: 的默认转换:
Live On Compiler Explorer
#include <iostream>
#include <boost/json/src.hpp> // for header-only
namespace json = boost::json;
struct Im { std::array<std::uint64_t, 10> bits; };
int main()
{
auto im = std::make_unique<Im>(
Im { 0b0010'1100'1010'0010'0111'1100'0010, /*...*/ });
std::cout << json::object{ {"Image1", json::value_from(im->bits) } };
}
打印
{"Image1":[46802882,0,0,0,0,0,0,0,0,0]}