|
| 1 | +package com.fasterxml.jackson.failing; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +import com.fasterxml.jackson.databind.*; |
| 6 | + |
| 7 | +public class EnumAsIndexMapKey2129Test extends BaseMapTest |
| 8 | +{ |
| 9 | + // [databind#2129] |
| 10 | + public enum Type { |
| 11 | + FIRST, |
| 12 | + SECOND; |
| 13 | + } |
| 14 | + |
| 15 | + static class TypeContainer { |
| 16 | + public Map<Type, Integer> values; |
| 17 | + |
| 18 | + public TypeContainer(Type type, int value) { |
| 19 | + values = Collections.singletonMap(type, value); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + final ObjectMapper MAPPER = newJsonMapper(); |
| 24 | + |
| 25 | + // [databind#2129] |
| 26 | + public void testEnumAsIndexForRootMap() throws Exception |
| 27 | + { |
| 28 | + final Map<Type, Integer> input = Collections.singletonMap(Type.FIRST, 3); |
| 29 | + |
| 30 | + // by default, write using name() |
| 31 | + assertEquals(aposToQuotes("{'FIRST':3}"), |
| 32 | + MAPPER.writeValueAsString(input)); |
| 33 | + |
| 34 | + // but change with setting |
| 35 | + assertEquals(aposToQuotes("{'0':3}"), |
| 36 | + MAPPER.writer() |
| 37 | + .with(SerializationFeature.WRITE_ENUM_KEYS_USING_INDEX) |
| 38 | + .writeValueAsString(input)); |
| 39 | + |
| 40 | + // but NOT with value settings |
| 41 | + assertEquals(aposToQuotes("{'FIRST':3}"), |
| 42 | + MAPPER.writer() |
| 43 | + .with(SerializationFeature.WRITE_ENUMS_USING_INDEX) |
| 44 | + .writeValueAsString(input)); |
| 45 | + } |
| 46 | + |
| 47 | + // [databind#2129] |
| 48 | + public void testEnumAsIndexForValueMap() throws Exception |
| 49 | + { |
| 50 | + final TypeContainer input = new TypeContainer(Type.SECOND, 72); |
| 51 | + |
| 52 | + // by default, write using name() |
| 53 | + assertEquals(aposToQuotes("{'values':{'SECOND':72}}"), |
| 54 | + MAPPER.writeValueAsString(input)); |
| 55 | + |
| 56 | + // but change with setting |
| 57 | + assertEquals(aposToQuotes("{'values':{'1':72}}"), |
| 58 | + MAPPER.writer() |
| 59 | + .with(SerializationFeature.WRITE_ENUM_KEYS_USING_INDEX) |
| 60 | + .writeValueAsString(input)); |
| 61 | + |
| 62 | + // but NOT with value settings |
| 63 | + assertEquals(aposToQuotes("{'values':{'SECOND':72}}"), |
| 64 | + MAPPER.writer() |
| 65 | + .with(SerializationFeature.WRITE_ENUMS_USING_INDEX) |
| 66 | + .writeValueAsString(input)); |
| 67 | + } |
| 68 | +} |
0 commit comments