Skip to content

Commit f390883

Browse files
committed
Add WebFlux SSE support with GSON
Closes gh-35884
1 parent c10266e commit f390883

File tree

3 files changed

+7
-2
lines changed

3 files changed

+7
-2
lines changed

spring-web/src/main/java/org/springframework/http/codec/json/GsonEncoder.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
import org.springframework.core.io.buffer.DataBufferFactory;
3838
import org.springframework.http.MediaType;
3939
import org.springframework.http.codec.HttpMessageEncoder;
40+
import org.springframework.http.codec.ServerSentEvent;
4041
import org.springframework.util.Assert;
4142
import org.springframework.util.FastByteArrayOutputStream;
4243
import org.springframework.util.MimeType;
@@ -106,7 +107,8 @@ public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType
106107
if (!super.canEncode(elementType, mimeType)) {
107108
return false;
108109
}
109-
return !String.class.isAssignableFrom(elementType.toClass());
110+
Class<?> elementClass = elementType.toClass();
111+
return !(String.class.isAssignableFrom(elementClass) || ServerSentEvent.class.isAssignableFrom(elementClass));
110112
}
111113

112114
@Override

spring-web/src/main/java/org/springframework/http/codec/support/ServerDefaultCodecsImpl.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ protected void extendObjectWriters(List<HttpMessageWriter<?>> objectWriters) {
5858
private @Nullable Encoder<?> getSseEncoder() {
5959
return this.sseEncoder != null ? this.sseEncoder :
6060
(JACKSON_PRESENT || JACKSON_2_PRESENT) ? getJacksonJsonEncoder() :
61+
GSON_PRESENT ? getGsonEncoder() :
6162
KOTLIN_SERIALIZATION_JSON_PRESENT ? getKotlinSerializationJsonEncoder() :
6263
null;
6364
}

spring-web/src/test/java/org/springframework/http/codec/json/GsonEncoderTests.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import org.springframework.core.ResolvableType;
2424
import org.springframework.core.io.buffer.DataBuffer;
2525
import org.springframework.core.testfixture.codec.AbstractEncoderTests;
26+
import org.springframework.http.codec.ServerSentEvent;
2627
import org.springframework.web.testfixture.xml.Pojo;
2728

2829
import static org.assertj.core.api.Assertions.assertThat;
@@ -42,7 +43,8 @@ protected void canEncode() throws Exception {
4243
assertThat(this.encoder.canEncode(pojoType, APPLICATION_JSON)).isTrue();
4344
assertThat(this.encoder.canEncode(pojoType, APPLICATION_NDJSON)).isTrue();
4445
assertThat(this.encoder.canEncode(pojoType, null)).isTrue();
45-
46+
assertThat(this.encoder.canEncode(ResolvableType.forClass(ServerSentEvent.class), null)).isFalse();
47+
assertThat(this.encoder.canEncode(ResolvableType.forClass(String.class), null)).isFalse();
4648
}
4749

4850
@Test

0 commit comments

Comments
 (0)