问题
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