반응형
enum 을 json으로 변환할 때 커스터마이징 하는 방법입니다.
Source
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; public class Test { public enum Number { _1, _2, _3; @JsonValue public Integer toValue() { return Integer.parseInt(this.name().replace("_", "")); } } public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); Map<Number, String> map = new LinkedHashMap<>(); map.put(Number._1, "one"); map.put(Number._2, "two"); String writeValueAsString = mapper.writer().writeValueAsString(map); System.out.println(writeValueAsString); Map<Number, String> map2 = mapper.readValue(writeValueAsString, new TypeReference<Map<Number, String>>() { }); System.out.println(map2.get(Number._1)); System.out.println(map2.get(Number._2)); } } |
Result
1 2 3 | {"1":"one","2":"two"} one two |
Result Without @JsonValue
1 2 3 | {"_1":"one","_2":"two"} one two |
반응형
'java' 카테고리의 다른 글
spring boot logging.config (0) | 2018.09.10 |
---|---|
restTemplate large file download stream (0) | 2018.09.03 |
java - pretty log - 예쁜 로그를 남기자! (0) | 2018.08.30 |
java php aes ecb nopadding (2) | 2018.08.29 |
[tomcat-jdbc] Found class org.apache.juli.logging.Log, but interface was expected (0) | 2018.08.24 |
Spring RestTemplate Request Parameter Encoding (0) | 2018.08.16 |
spring boot main args - ApplicationArguments (0) | 2018.08.16 |
java file create time (0) | 2018.08.13 |