Reputation: 585
I have these two classes:
Foo.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Foo {
private ListWrapper data;
}
ListWrapper.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ListWrapper {
@JsonValue
private List<String> value;
}
I am using the following method to test serialization:
public void testSerialization() throws JsonProcessingException {
Foo foo = new Foo();
foo.setData(new ListWrapper(new ArrayList<String>() {
{
add("foo");
add("bar");
}
}));
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(foo));
}
The output is {"data":["foo","bar"]}
. Now I am trying to deserialize this json string with the following method:
public void testDeserialization() throws IOException {
String json = "{\"data\":[\"foo\",\"bar\"]}";
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(json, Foo.class));
}
But this does not work. I am getting the following exception:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `ListWrapper` out of START_ARRAY token
at [Source: (String)"{"data":["foo","bar"]}"; line: 1, column: 9] (through reference chain: Foo["data"])
I have no clue why this is happening. Can anyone give me a hint? I am using Jackson 2.9.9.
Upvotes: 4
Views: 1892
Reputation: 1072
The exception is thrown by Jackson object mapper as it is expecting Object
type for data
attribute, but Array
was found instead.
@JsonValue
annotation is used for marshalling. The analogous annotation for unmarshalling is @JsonCreator
.
Annotate your ListWrapper
constructor
@JsonCreator
public ListWrapper(List<String> value) {
this.value = value;
}
Upvotes: 4