Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.72 KB | None | 0 0
  1. import com.fasterxml.jackson.annotation.JsonProperty;
  2. import com.fasterxml.jackson.core.type.TypeReference;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4.  
  5. import java.io.IOException;
  6.  
  7.  
  8. public class ObjectMapperGeneric {
  9.  
  10.  
  11.     public static void main(String[] args) {
  12.         String jsonOne = "{\"code\":\"my code\", \"value\":\"some value\"}";
  13.         String jsonTwo = "{\"number\":1, \"value\":\"some value\"}";
  14.         try {
  15.  
  16.             DtoOne one = new ObjectMapperGeneric().jsonGeneric(jsonOne);
  17.             DtoOne two = new ObjectMapperGeneric().jsonGeneric(jsonTwo);
  18.  
  19.             System.out.println();
  20.         } catch (Exception e){
  21.             e.printStackTrace();
  22.         }
  23.     }
  24.  
  25.  
  26.     private <T> T jsonGeneric(String json) throws IOException {
  27.         ObjectMapper mapper = new ObjectMapper();
  28.         return mapper.readValue(json, new TypeReference<T>(){});
  29.  
  30.     }
  31. }
  32.  
  33. class DtoOne{
  34.     @JsonProperty("code")
  35.     private String code;
  36.  
  37.     @JsonProperty("value")
  38.     private String value;
  39.  
  40.     public String getCode() {
  41.         return code;
  42.     }
  43.  
  44.     public void setCode(String code) {
  45.         this.code = code;
  46.     }
  47.  
  48.     public String getValue() {
  49.         return value;
  50.     }
  51.  
  52.     public void setValue(String value) {
  53.         this.value = value;
  54.     }
  55. }
  56.  
  57. class DtoTwo{
  58.     @JsonProperty("number")
  59.     private Integer number;
  60.  
  61.     @JsonProperty("value")
  62.     private String value;
  63.  
  64.     public Integer getNumber() {
  65.         return number;
  66.     }
  67.  
  68.     public void setNumber(Integer number) {
  69.         this.number = number;
  70.     }
  71.  
  72.     public String getValue() {
  73.         return value;
  74.     }
  75.  
  76.     public void setValue(String value) {
  77.         this.value = value;
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement