Refine `JsonWriter` for structured logging

Add `formatToBytes()` method for use with structured logging.

See gh-41491
This commit is contained in:
Phillip Webb 2024-07-24 17:59:31 +01:00
parent 700c1e8f82
commit 50dbaec2d0
2 changed files with 30 additions and 0 deletions

View File

@ -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<T> {
}
}
/**
* 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.

View File

@ -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");