Search code examples
javajsonjacksonjson-api

Jackson deserialize single item into list


I'm trying to consume a service that gives me an entity with a field that it's an array.

{
  "id": "23233",
  "items": [
    {
      "name": "item 1"
    },
    {
      "name": "item 2"
    }
  ]
}

But when the array contains a single item, the item itself is returned, instead of an array of one element.

{
  "id": "43567",
  "items": {
      "name": "item only"
    }
}

In this case, Jackson fails to convert to my Java object.

public class ResponseItem {

   private String id;
   private List<Item> items;

   //Getters and setters...
}

Is there an straightforward solution for it?


Solution

  • You are not the first to ask for this problem. It seems pretty old.

    After looking at this problem, you can use the DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY :

    Look at the documentation : http://fasterxml.github.io/jackson-databind/javadoc/2.5/com/fasterxml/jackson/databind/DeserializationFeature.html#ACCEPT_SINGLE_VALUE_AS_ARRAY

    You need to add this jackson feature to your object mapper.

    I hope it will help you.