Deserializing JSON into object with overloaded methods using Jackson

后端 未结 3 1153
遥遥无期
遥遥无期 2020-12-07 22:36

I am attempting to deserialize a JSON object stored in CouchDb using Jackson. This object needs to deserialize into a pojo that contains overloaded methods. When I attempt

相关标签:
3条回答
  • 2020-12-07 22:44

    It's not necessary to change the name of the setter method to avoid ambiguity. You're otherwise on the right track with @JsonIgnore. With @JsonIgnore on all of the same-named methods to be ignored, the one to use does not need the @JsonProperty annotation.

    Here's a simple example to demonstrate this point.

    input.json: {"value":"forty-two"}

    Foo.java:

    import java.io.File;
    
    import org.codehaus.jackson.annotate.JsonIgnore;
    import org.codehaus.jackson.map.ObjectMapper;
    
    public class Foo
    {
      String value;
    
      public String getValue() {return value;}
      public void setValue(String value) {this.value = value;}
    
      @JsonIgnore
      public void setValue(int value) {this.value = String.valueOf(value);}
    
      public static void main(String[] args) throws Exception
      {
        ObjectMapper mapper = new ObjectMapper();
        Foo foo = mapper.readValue(new File("input.json"), Foo.class);
        System.out.println(mapper.writeValueAsString(foo));
      }
    }
    

    If you don't want to alter the pristine POJO defs with a Jackson annotation, then you can use a MixIn.

    import java.io.File;
    
    import org.codehaus.jackson.annotate.JsonIgnore;
    import org.codehaus.jackson.map.ObjectMapper;
    
    public class Foo
    {
      String value;
    
      public String getValue() {return value;}
      public void setValue(String value) {this.value = value;}
      public void setValue(int value) {this.value = String.valueOf(value);}
    
      public static void main(String[] args) throws Exception
      {
        ObjectMapper mapper = new ObjectMapper();
        mapper.getDeserializationConfig().addMixInAnnotations(Foo.class, IgnoreFooSetValueIntMixIn.class);
        Foo foo = mapper.readValue(new File("input.json"), Foo.class);
        System.out.println(mapper.writeValueAsString(foo));
      }
    }
    
    abstract class IgnoreFooSetValueIntMixIn
    {
      @JsonIgnore public abstract void setValue(int value);
    }
    
    0 讨论(0)
  • 2020-12-07 22:45

    In cases where @JsonIgnore doesn't help (I currently have such a case, but am still unsure of the reason), it is also possible to use @XmlTransient instead.

    0 讨论(0)
  • 2020-12-07 22:58

    In Jackson > 2.4 use directly :

    mapper.addMixIn(Foo.class, IgnoreFooSetValueIntMixIn.class);
    
    0 讨论(0)
提交回复
热议问题