boost::json 如何序列化到文件 (std::ofstream) 最小示例
serialize_to_file.cpp
#include <boost/json.hpp>
#include <fstream>
#include <iostream>
namespace json = boost::json;
int main() {
// Create a JSON object
json::object obj{
{"name", "John Doe"},
{"age", 30},
{"city", "New York"}
};
// Open the output file stream
std::ofstream file("output.json");
if (file.is_open()) {
// Serialize the JSON object and write it to the file
file << obj;
// Close the file stream
file.close();
std::cout << "JSON object serialized and written to file successfully." << std::endl;
} else {
std::cout << "Unable to open file for writing." << std::endl;
}
return 0;
}使用以下命令编译:
build_boostjson.sh
g++ -o main main.cpp -lboost_json使用 ./main 运行程序后,output.json 将如下所示:
output.json
{"name":"John Doe","age":30,"city":"New York"}Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow