Deserializing to object with overloaded setter with fasterxml.jackson

半世苍凉 提交于 2021-01-28 00:24:18

问题


I want to deserialize json string into object which have overloaded setter for a field. I don't want to explicitly annotate one of the setter with @JsonIgnore. Why can't jackson library use appropriate setter according to the type of value it fetches in json string? Following is Code:

public class A {

Set<Integer> set = new HashSet<Integer>();

public Set<Integer> getSet() {
    return set;
}

public void setSet(Set<Integer> set) {
    this.set = set;
}

public void setSet(String str)
{
    this.set = null;
}
}
=========================
String input = "{\"set\":[1,4,6]}";

A b = mapper.readValue(input, A.class);

System.out.println(b.getSet());

I got following error:

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_ARRAY token
 at [Source: (String)"{"set":[1,4,6]}"; line: 1, column: 8] (through reference chain: com.rs.multiplesetter.A["set"])

回答1:


Jackson not accept multiple setter. You need to specify the one setter by @JsonSetter. If you want to accept multiple type then you can handle this using JsonNode. Here is example:

public class A implements Serializable{

private static final long serialVersionUID = 1L;

Set<Integer> set = new HashSet<Integer>();

public Set<Integer> getSet() {
    return set;
}

public void setSet(Set<Integer> set) {
    this.set = set;
}

public void setSet(String str)
{
    this.set = null;
}

@JsonSetter
public void setSet(JsonNode jsonNode){
     //handle here as per your requirement
    if(jsonNode.getNodeType().equals(JsonNodeType.STRING)){
        this.set = null;
    }else if(jsonNode.getNodeType().equals(JsonNodeType.ARRAY)){
        try{
            ObjectReader reader = new ObjectMapper().readerFor(new TypeReference<Set<Integer>>() {});
            this.set = reader.readValue(jsonNode);
        }catch (Exception ex){
        }
    }
}
}

**If you dont want to handle here then you can use custom deserialization class.



来源:https://stackoverflow.com/questions/51538990/deserializing-to-object-with-overloaded-setter-with-fasterxml-jackson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!