Jersey/Jackson @JsonIgnore on setter

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

i have an class with the following annotations:

class A {
public Map> references;

@JsonProperty
public Map

        
5条回答
  •  情书的邮戳
    2021-02-13 19:12

    I can only think of a non-jackson solution, to use a base class that does not have references for the mapping and then cast to the actual class:

    // expect a B on an incoming request
    class B {
    // ...
    }
    
    // after the data is read, cast to A which will have empty references
    class A extends B {
    public Map> references;
    }
    

    Why do you even send the References if you don't want them?

    Or is the incoming data out of your hands and you just want to avoid the mapping exception telling you that jackson cannot find a property to set for incoming references? For that we use a base class which all of our Json model classes inherit:

    public abstract class JsonObject {
    
        @JsonAnySetter
        public void handleUnknown(String key, Object value) {
    
            // for us we log an error if we can't map but you can skip that
            Log log = LogFactory.getLog(String.class);    
            log.error("Error mapping object of type: " + this.getClass().getName());    
            log.error("Could not map key: \"" + key + "\" and value: \"" + "\"" + value.toString() + "\"");
    
        }
    

    Then in the POJO you add @JsonIgnoreProperties so that incoming properties will get forwarded to handleUnknown()

    @JsonIgnoreProperties
    class A extends JsonObject {
        // no references if you don't need them
    }
    

    edit

    This SO Thread describes how to use Mixins. This might be the solution, if you want to keep your structure exactly as it is, but I have not tried it.

提交回复
热议问题