Skip to content

Commit 99fc2ec

Browse files
committed
add unit test for #827 to show the problem
1 parent 93d5900 commit 99fc2ec

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package com.fasterxml.jackson.databind.seq;
2+
3+
import java.io.IOException;
4+
import java.util.HashMap;
5+
import java.util.Map;
6+
7+
import org.junit.Assert;
8+
import org.junit.Test;
9+
10+
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
11+
import com.fasterxml.jackson.annotation.PropertyAccessor;
12+
import com.fasterxml.jackson.core.JsonGenerator;
13+
import com.fasterxml.jackson.core.JsonProcessingException;
14+
import com.fasterxml.jackson.databind.*;
15+
import com.fasterxml.jackson.databind.SerializerProvider;
16+
import com.fasterxml.jackson.databind.module.SimpleModule;
17+
import com.fasterxml.jackson.databind.type.MapType;
18+
19+
// for [databind#827]
20+
public class PolyMapWriterTest extends BaseMapTest
21+
{
22+
static class CustomKey {
23+
String a;
24+
int b;
25+
26+
public String toString() { return "BAD-KEY"; }
27+
}
28+
29+
public class CustomKeySerializer extends JsonSerializer<CustomKey> {
30+
@Override
31+
public void serialize(CustomKey key, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
32+
jsonGenerator.writeFieldName(key.a + "," + key.b);
33+
}
34+
}
35+
36+
@Test
37+
public void testPolyCustomKeySerializer() throws Exception {
38+
ObjectMapper mapper = new ObjectMapper();
39+
mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
40+
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
41+
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
42+
43+
SimpleModule module = new SimpleModule("keySerializerModule");
44+
module.addKeySerializer(CustomKey.class, new CustomKeySerializer());
45+
mapper.registerModule(module);
46+
47+
Map<CustomKey, String> map = new HashMap<CustomKey, String>();
48+
CustomKey key = new CustomKey();
49+
key.a = "foo";
50+
key.b = 1;
51+
map.put(key, "bar");
52+
53+
final MapType type = mapper.getTypeFactory().constructMapType(
54+
Map.class, CustomKey.class, String.class);
55+
final ObjectWriter writer = mapper.writerFor(type);
56+
String json = writer.writeValueAsString(map);
57+
58+
Assert.assertEquals("[\"java.util.HashMap\",{\"foo,1\":\"bar\"}]", json);
59+
}
60+
61+
}

0 commit comments

Comments
 (0)