Skip to content

Commit 50dbaec

Browse files
committed
Refine JsonWriter for structured logging
Add `formatToBytes()` method for use with structured logging. See gh-41491
1 parent 700c1e8 commit 50dbaec

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

spring-boot-project/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
package org.springframework.boot.json;
1818

19+
import java.io.ByteArrayOutputStream;
1920
import java.io.IOException;
2021
import java.io.OutputStream;
2122
import java.io.OutputStreamWriter;
@@ -187,6 +188,29 @@ default String toJsonString() {
187188
}
188189
}
189190

191+
/**
192+
* Write the JSON to a UTF-8 encoded byte array.
193+
* @return the JSON bytes
194+
*/
195+
default byte[] toByteArray() {
196+
return toByteArray(StandardCharsets.UTF_8);
197+
}
198+
199+
/**
200+
* Write the JSON to a byte array.
201+
* @param charset the charset
202+
* @return the JSON bytes
203+
*/
204+
default byte[] toByteArray(Charset charset) {
205+
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
206+
toWriter(new OutputStreamWriter(out, charset));
207+
return out.toByteArray();
208+
}
209+
catch (IOException ex) {
210+
throw new UncheckedIOException(ex);
211+
}
212+
}
213+
190214
/**
191215
* Write the JSON to the provided {@link WritableResource} using
192216
* {@link StandardCharsets#UTF_8 UTF8} encoding.

spring-boot-project/spring-boot/src/test/java/org/springframework/boot/json/JsonWriterTests.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,12 @@ void toJsonStringWhenIOExceptionIsThrownThrowsUncheckedIOException() {
480480
.withMessage("bad");
481481
}
482482

483+
@Test
484+
void toByteArrayReturnsByteArray() {
485+
WritableJson writable = (out) -> out.append("{}");
486+
assertThat(writable.toByteArray()).isEqualTo("{}".getBytes());
487+
}
488+
483489
@Test
484490
void toResourceWritesJson() throws Exception {
485491
File file = new File(JsonWriterTests.this.temp, "out.json");

0 commit comments

Comments
 (0)