daydreamer
daydreamer

Reputation: 91939

Jackson: how to read a String as List?

Our current class looks like

public class Attributes {

  private String mapping;

  .....

and

{
  "mapping": "displayName",
  .....

This has worked well and shipped to customers.

The way we convert JSON to Attribute class is

JSON.readValue(jsonFile, Attribute.class);

Recently the requirement says, that mapping would be List<String> instead of String

At first, the quick change that I thought of was to change mapping to List<String>, but this would break existing clients.

I tried that by writing test that does

assertEquals("displayName", configuration.getMapping().get(0));  

and it failed as

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token

Question
How can I tell Jackson to read a String as `List? It would be List of 1 item but would be backward compatible.

Thanks

Upvotes: 1

Views: 237

Answers (1)

daydreamer
daydreamer

Reputation: 91939

The answer is Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

Upvotes: 2

Related Questions