|
| 1 | +package com.baeldung.jackson.serialization; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +import org.junit.Assert; |
| 7 | +import org.junit.Test; |
| 8 | + |
| 9 | +import com.baeldung.jackson.entities.MyPair; |
| 10 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 11 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 12 | +import com.fasterxml.jackson.databind.annotation.JsonSerialize; |
| 13 | +import com.fasterxml.jackson.databind.ser.std.MapSerializer; |
| 14 | + |
| 15 | +public class JacksonMapSerializeTest { |
| 16 | + |
| 17 | + @JsonSerialize(keyUsing = MyPairSerializer.class) |
| 18 | + private Map<MyPair, String> map; |
| 19 | + |
| 20 | + @JsonSerialize(keyUsing = MapSerializer.class) |
| 21 | + private Map<MyPair, MyPair> cmap; |
| 22 | + |
| 23 | + @JsonSerialize(keyUsing = MyPairSerializer.class) |
| 24 | + private MyPair mapKey; |
| 25 | + |
| 26 | + @JsonSerialize(keyUsing = MyPairSerializer.class) |
| 27 | + private MyPair mapValue; |
| 28 | + |
| 29 | + @Test |
| 30 | + public void whenSimpleMapSerialize_thenCorrect() |
| 31 | + throws JsonProcessingException { |
| 32 | + |
| 33 | + Map<String, String> map = new HashMap<String, String>(); |
| 34 | + map.put("key", "value"); |
| 35 | + |
| 36 | + final ObjectMapper mapper = new ObjectMapper(); |
| 37 | + final String jsonResult = mapper.writeValueAsString(map); |
| 38 | + |
| 39 | + Assert.assertEquals("{\"key\":\"value\"}", jsonResult); |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + public void whenCustomObjectStringMapSerialize_thenCorrect() |
| 44 | + throws JsonProcessingException { |
| 45 | + |
| 46 | + map = new HashMap<MyPair, String>(); |
| 47 | + MyPair key = new MyPair("Abbott", "Costello"); |
| 48 | + map.put(key, "Comedy"); |
| 49 | + |
| 50 | + final ObjectMapper mapper = new ObjectMapper(); |
| 51 | + final String jsonResult = mapper.writeValueAsString(map); |
| 52 | + |
| 53 | + Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult); |
| 54 | + } |
| 55 | + |
| 56 | + @Test |
| 57 | + public void whenCustomObjectObjectMapSerialize_thenCorrect() |
| 58 | + throws JsonProcessingException { |
| 59 | + |
| 60 | + cmap = new HashMap<MyPair, MyPair>(); |
| 61 | + mapKey = new MyPair("Abbott", "Costello"); |
| 62 | + mapValue = new MyPair("Comedy", "1940's"); |
| 63 | + cmap.put(mapKey, mapValue); |
| 64 | + |
| 65 | + final ObjectMapper mapper = new ObjectMapper(); |
| 66 | + final String jsonResult = mapper.writeValueAsString(cmap); |
| 67 | + |
| 68 | + Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}", |
| 69 | + jsonResult); |
| 70 | + } |
| 71 | +} |
0 commit comments