diff --git a/spring-web-reactive/src/main/java/org/springframework/core/codec/support/StringDecoder.java b/spring-web-reactive/src/main/java/org/springframework/core/codec/support/StringDecoder.java index 090adca2d0..d23da9b43d 100644 --- a/spring-web-reactive/src/main/java/org/springframework/core/codec/support/StringDecoder.java +++ b/spring-web-reactive/src/main/java/org/springframework/core/codec/support/StringDecoder.java @@ -16,6 +16,7 @@ package org.springframework.core.codec.support; +import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -39,6 +40,7 @@ import org.springframework.util.MimeTypeUtils; * @author Sebastien Deleuze * @author Brian Clozel * @author Arjen Poutsma + * @author Mark Paluch * @see StringEncoder */ public class StringDecoder extends AbstractDecoder { @@ -83,9 +85,8 @@ public class StringDecoder extends AbstractDecoder { } Charset charset = getCharset(mimeType); return inputFlux.map(content -> { - byte[] bytes = new byte[content.readableByteCount()]; - content.read(bytes); - return new String(bytes, charset); + CharBuffer charBuffer = charset.decode(content.asByteBuffer()); + return charBuffer.toString(); }); } diff --git a/spring-web-reactive/src/test/java/org/springframework/core/codec/support/StringDecoderTests.java b/spring-web-reactive/src/test/java/org/springframework/core/codec/support/StringDecoderTests.java index 44af9239a5..b5f83fbc04 100644 --- a/spring-web-reactive/src/test/java/org/springframework/core/codec/support/StringDecoderTests.java +++ b/spring-web-reactive/src/test/java/org/springframework/core/codec/support/StringDecoderTests.java @@ -33,6 +33,7 @@ import static org.junit.Assert.*; /** * @author Sebastien Deleuze * @author Brian Clozel + * @author Mark Paluch */ public class StringDecoderTests extends AbstractAllocatingTestCase { @@ -94,4 +95,13 @@ public class StringDecoderTests extends AbstractAllocatingTestCase { assertEquals("foobar", result); } + @Test + public void decodeEmpty() throws InterruptedException { + Mono source = Mono.just(stringBuffer("")); + Flux output = + this.decoder.decode(source, ResolvableType.forClass(String.class), null); + TestSubscriber testSubscriber = new TestSubscriber<>(); + testSubscriber.bindTo(output).assertValues(""); + } + }