Annotation for binding a json field to a field in POJO with a different name

前端 未结 2 661
感动是毒
感动是毒 2021-01-25 06:05

Java class (used as a Data Transfer Object):

class Resource also has a field named id with a different type along with its getter and setter, hence the synt

相关标签:
2条回答
  • 2021-01-25 06:49

    Googled and found this question: Jackson serialization: how to ignore superclass properties. Adapted it for your problem.

    public class A extends B {
        private int id;
    
        public A(int id) {
            super.setId("id" + id);
            this.id = id;
        }
    
        @Override
        @JsonProperty("_id_")
        public String getId() {
            return super.getId();
        }
    
        @Override
        @JsonProperty("_id_")
        public void setId(String id) {
            super.setId(id);
        }
    
        @JsonProperty("id")
        public int getIntId() {
            return id;
        }
    
        @JsonProperty("id")
        public void setIntId(int id) {
            this.id = id;
        }
    }
    
    public class B {
        private String id;
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    }
    

    Tested it with this:

    @RestController
    public class TestController {
        @GetMapping("/test")
        public A test() {
            return new A(1);
        }
    }
    

    And the output was:

    {
      "_id_": "id1",
      "id": 1
    }
    
    0 讨论(0)
  • 2021-01-25 06:56
    public A extends Resource {
        private int id;
    
        @JsonProperty("_id")
        public int getId() {
          return id;
        }
    
        @JsonProperty("id")
        public void setId(int id) {
          this.id = id;
        }
    }
    

    the method names should be different, so jackson parses it as different fields, not as one field.

    0 讨论(0)
提交回复
热议问题