|
| 1 | +package com.fasterxml.jackson.databind.ser; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.core.type.TypeReference; |
| 5 | +import com.fasterxml.jackson.databind.DeserializationContext; |
| 6 | +import com.fasterxml.jackson.databind.KeyDeserializer; |
| 7 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 8 | +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; |
| 9 | +import com.fasterxml.jackson.databind.module.SimpleModule; |
| 10 | +import org.junit.jupiter.api.Test; |
| 11 | + |
| 12 | +import java.io.IOException; |
| 13 | +import java.util.Map; |
| 14 | + |
| 15 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 16 | + |
| 17 | +// [databind#4444] |
| 18 | +public class TestKeyDeserializerOverwritten { |
| 19 | + @JsonDeserialize(keyUsing = ForClass.class) |
| 20 | + static class MyKey { |
| 21 | + private final String value; |
| 22 | + |
| 23 | + MyKey(String value) { |
| 24 | + this.value = value; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + static class ForClass extends KeyDeserializer { |
| 29 | + @Override |
| 30 | + public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { |
| 31 | + return new MyKey(key + "-class"); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + static class ForMapper extends KeyDeserializer { |
| 36 | + @Override |
| 37 | + public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException { |
| 38 | + return new MyKey(key + "-mapper"); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + TypeReference<Map<MyKey, String>> typeRef = new TypeReference<>() {}; |
| 43 | + |
| 44 | + @Test |
| 45 | + void withoutForClass() throws JsonProcessingException { |
| 46 | + ObjectMapper mapper = new ObjectMapper(); |
| 47 | + Map<MyKey, String> result = mapper.readValue("{\"foo\":null}", typeRef); |
| 48 | + |
| 49 | + assertEquals("foo-class", result.keySet().stream().findFirst().get().value); |
| 50 | + } |
| 51 | + |
| 52 | + // The KeyDeserializer set by the annotation must not be overwritten by the KeyDeserializer set in the mapper. |
| 53 | + @Test |
| 54 | + void withForClass() throws JsonProcessingException { |
| 55 | + SimpleModule sm = new SimpleModule(); |
| 56 | + sm.addKeyDeserializer(MyKey.class, new ForMapper()); |
| 57 | + |
| 58 | + ObjectMapper mapper = new ObjectMapper().registerModule(sm); |
| 59 | + Map<MyKey, String> result = mapper.readValue("{\"foo\":null}", typeRef); |
| 60 | + |
| 61 | + assertEquals("foo-class", result.keySet().stream().findFirst().get().value); |
| 62 | + } |
| 63 | +} |
0 commit comments