File tree Expand file tree Collapse file tree 2 files changed +30
-0
lines changed
spring-boot-project/spring-boot/src
main/java/org/springframework/boot/json
test/java/org/springframework/boot/json Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Original file line number Diff line number Diff line change 16
16
17
17
package org .springframework .boot .json ;
18
18
19
+ import java .io .ByteArrayOutputStream ;
19
20
import java .io .IOException ;
20
21
import java .io .OutputStream ;
21
22
import java .io .OutputStreamWriter ;
@@ -187,6 +188,29 @@ default String toJsonString() {
187
188
}
188
189
}
189
190
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
+
190
214
/**
191
215
* Write the JSON to the provided {@link WritableResource} using
192
216
* {@link StandardCharsets#UTF_8 UTF8} encoding.
Original file line number Diff line number Diff line change @@ -480,6 +480,12 @@ void toJsonStringWhenIOExceptionIsThrownThrowsUncheckedIOException() {
480
480
.withMessage ("bad" );
481
481
}
482
482
483
+ @ Test
484
+ void toByteArrayReturnsByteArray () {
485
+ WritableJson writable = (out ) -> out .append ("{}" );
486
+ assertThat (writable .toByteArray ()).isEqualTo ("{}" .getBytes ());
487
+ }
488
+
483
489
@ Test
484
490
void toResourceWritesJson () throws Exception {
485
491
File file = new File (JsonWriterTests .this .temp , "out.json" );
You can’t perform that action at this time.
0 commit comments