简体   繁体   中英

Jackson ObjectMapper deserialize an object which contains an array of objects

I serialize this kind of object:

public class MyObject implements Serializable {

private String type;
...
private String[] target;

//getters and setters
}

But when I try to deserialize MyObject I get an error because of the target array.

java.lang.RuntimeException: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_ARRAY token
at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: java.util.ArrayList[0]->MyObject["target"])
...

How can I deserialize an array ?

I finally found the problem. I did not see I had 2 setters in the class. Jackson was probably using the wrong one.

I just had to put the annotation @JsonSetter("target") above the setter which accept an array to tell Jackson to use the good one.

public void setTarget(String target) {
    this.target = new String[]{target};
}

@JsonSetter("target")
public void setTarget(String[] target) {
    this.target = target;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM