Add custom deserializers support to AbstractJackson2Decoder

Issue: SPR-15975
This commit is contained in:
Sebastien Deleuze
2017-09-25 23:17:32 +02:00
parent e927cae476
commit 74120ef00f
2 changed files with 51 additions and 1 deletions

View File

@@ -16,12 +16,19 @@
package org.springframework.http.codec.json;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -32,6 +39,7 @@ import org.springframework.core.codec.CodecException;
import org.springframework.core.codec.DecodingException;
import org.springframework.core.io.buffer.AbstractDataBufferAllocatingTestCase;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.codec.Pojo;
import org.springframework.util.MimeType;
@@ -210,6 +218,19 @@ public class Jackson2JsonDecoderTests extends AbstractDataBufferAllocatingTestCa
StepVerifier.create(flux).verifyError(CodecException.class);
}
@Test // SPR-15975
public void customDeserializer() {
DataBuffer buffer = new DefaultDataBufferFactory().wrap("{\"test\": 1}".getBytes());
Jackson2JsonDecoder decoder = new Jackson2JsonDecoder(new ObjectMapper());
Flux<TestObject> decoded = decoder.decode(Mono.just(buffer),
ResolvableType.forClass(TestObject.class), null, null).cast(TestObject.class);
StepVerifier.create(decoded)
.assertNext(v -> assertEquals(1, v.getTest()))
.verifyComplete();
}
private static class BeanWithNoDefaultConstructor {
@@ -232,4 +253,33 @@ public class Jackson2JsonDecoderTests extends AbstractDataBufferAllocatingTestCa
}
@JsonDeserialize(using = Deserializer.class)
public static class TestObject {
private int test;
public int getTest() {
return test;
}
public void setTest(int test) {
this.test = test;
}
}
public static class Deserializer extends StdDeserializer<TestObject> {
private static final long serialVersionUID = 1L;
protected Deserializer() {
super(TestObject.class);
}
@Override
public TestObject deserialize(JsonParser p,
DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode node = p.readValueAsTree();
TestObject result = new TestObject();
result.setTest(node.get("test").asInt());
return result;
}
}
}