diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java index 0f91c2137b..a6eb1913a6 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java @@ -16,6 +16,7 @@ package org.springframework.boot.json; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; @@ -187,6 +188,29 @@ public interface JsonWriter { } } + /** + * Write the JSON to a UTF-8 encoded byte array. + * @return the JSON bytes + */ + default byte[] toByteArray() { + return toByteArray(StandardCharsets.UTF_8); + } + + /** + * Write the JSON to a byte array. + * @param charset the charset + * @return the JSON bytes + */ + default byte[] toByteArray(Charset charset) { + try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { + toWriter(new OutputStreamWriter(out, charset)); + return out.toByteArray(); + } + catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + /** * Write the JSON to the provided {@link WritableResource} using * {@link StandardCharsets#UTF_8 UTF8} encoding. diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/JsonWriterTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/JsonWriterTests.java index 1288977a94..12dd32f7ef 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/JsonWriterTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/JsonWriterTests.java @@ -480,6 +480,12 @@ public class JsonWriterTests { .withMessage("bad"); } + @Test + void toByteArrayReturnsByteArray() { + WritableJson writable = (out) -> out.append("{}"); + assertThat(writable.toByteArray()).isEqualTo("{}".getBytes()); + } + @Test void toResourceWritesJson() throws Exception { File file = new File(JsonWriterTests.this.temp, "out.json");