DocumentWriter
Header: swaggercpp/writer.hpp
Serialises Document back to JSON or YAML and offers a round-trip helper for format conversion.
Serialization preserves supported schema constraints and unmodeled fields stored in unknown_fields. Explicit empty security/server overrides remain distinct from omitted declarations. This is semantic preservation, not preservation of comments, whitespace, ordering, or every explicitly written default. Conversion does not migrate specification versions.
Recursive $ref strings remain references. A manually constructed cyclic SchemaPtr graph without a usable reference fails with an issue rather than recursing indefinitely. Prefer retained references or bundling when preparing recursive documents for output.
Options
Serialization bounds typed schema traversal to 256 nesting levels and 100,000 visits. Excessive expansion of a shared schema graph returns a failure issue. Keeping recursive and repeated structures as $ref avoids expanding them into repeated inline objects.
struct WriterOptions {
DocumentFormat format { DocumentFormat::yaml };
bool pretty { true };
int indent { 2 };
};API
class DocumentWriter {
public:
[[nodiscard]] static Result<std::string> write(const Document&, WriterOptions = {});
[[nodiscard]] static Result<std::string> write_json(const Document&, bool pretty = true, int indent = 2);
[[nodiscard]] static Result<std::string> write_yaml(const Document&);
[[nodiscard]] static Result<Document> roundtrip(std::string_view content, DocumentFormat output_format);
static Result<std::string> write_file(const Document&, const std::filesystem::path&, WriterOptions = {});
};write
Generic entry point that honours WriterOptions:
auto out = swaggercpp::DocumentWriter::write(doc, {
.format = swaggercpp::DocumentFormat::json,
.pretty = true,
.indent = 4,
});write_json / write_yaml
Shorthand for the common case:
auto json = swaggercpp::DocumentWriter::write_json(doc);
auto yaml = swaggercpp::DocumentWriter::write_yaml(doc);roundtrip
Parse content and re-serialise in the target format, without exposing the intermediate Document:
auto as_json = swaggercpp::DocumentWriter::roundtrip(
yaml_text, swaggercpp::DocumentFormat::json);This is the fastest path when you only need format conversion.
write_file
Serialises and writes to disk. Returns the produced content on success (same as write), so you can log or diff:
auto r = swaggercpp::DocumentWriter::write_file(doc, "out.yaml");
if (!r) return 1;
std::clog << "wrote " << r.value().size() << " bytes\n";Error cases
- Writing succeeds for any well-formed
Document. If the model has structural inconsistencies (e.g. cyclicSchemaPtr), the writer reportsIssueSeverity::errorentries andresult.ok()isfalse. write_fileadditionally fails on filesystem errors (permission denied, missing directory, etc.).