Jersey/Jackson @JsonIgnore on setter

后端 未结 5 1106
暗喜
暗喜 2021-02-13 18:28

i have an class with the following annotations:

class A {
public Map> references;

@JsonProperty
public Map

        
5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-13 19:08

    You have to make sure there is @JsonIgnore annotation on the field level as well as on the setter, and getter annotated with @JsonProperty.

    public class Echo {
    
        @Null
        @JsonIgnore
        private String doNotDeserialise;
    
        private String echo;
    
        @JsonProperty
        public String getDoNotDeserialise() {
            return doNotDeserialise;
        }
    
        @JsonIgnore
        public void setDoNotDeserialise(String doNotDeserialise) {
            this.doNotDeserialise = doNotDeserialise;
        }
    
        public String getEcho() {
            return echo;
        }
    
        public void setEcho(String echo) {
            this.echo = echo;
        }
    }
    
    @Controller
    public class EchoController {
    
    @ResponseBody
    @RequestMapping(value = "/echo", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
        public Echo echo(@RequestBody @Valid Echo echo) {
            if (StringUtils.isEmpty(echo.getDoNotDeserialise())) {
                echo.setDoNotDeserialise("Value is set by the server, not by the client!");
            }
    
            return echo;
        }
    }
    
    • If you submit a JSON request with a “doNotDeserialise” value set to something, when JSON is deserialised to an object it will be set to null (if not I put a validation constraint on the field so it will error out)
    • If you set the “doNotDeserialise” value to something on the server then it will be correctly serialised to JSON and pushed to the client

提交回复
热议问题