Jackson deserializes a single item to a list

I am trying to use a service that gives me an object with a field that is an array.

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

But when an array contains one element, the element itself is returned, not an array of one element.

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

In this case, Jackson cannot convert my Java object.

 public class ResponseItem { private String id; private List<Item> items; //Getters and setters... } 

Is there a direct solution for this?

+5
source share
3 answers

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

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

See documentation: http://fasterxml.imtqy.com/jackson-databind/javadoc/2.5/com/fasterxml/jackson/databind/DeserializationFeature.html#ACCEPT_SINGLE_VALUE_AS_ARRAY

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

Hope this helps you.

+8
source

To solve this problem, you can use a custom JsonDeserializer.

eg.

 class CustomDeserializer extends JsonDeserializer<List<Item>> { @Override public List<Item> deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException { JsonNode node = jsonParser.readValueAsTree(); List<Item> items = new ArrayList<>(); ObjectMapper mapper = new ObjectMapper(); if (node.size() == 1) { Item item = mapper.readValue(node.toString(), Item.class); items.add(item); } else { for (int i = 0; i < node.size(); i++) { Item item = mapper.readValue(node.get(i).toString(), Item.class); items.add(item); } } return items; } } 

you need to tell jackson to use it to deserialize items , for example:

 @JsonDeserialize(using = CustomDeserializer.class) private List<Item> items; 

After that it will work. Happy coding :)

+1
source

I'm pretty Gson capable of doing this without hiccups. Hope someone can help you with Jackson if you are stuck with him.

(example: fooobar.com/questions/79654 / ... )

EDITOR: Hehe, sorry to say, "I hope someone can help you ..." rather than "can not." It appeared rude.

-2
source

Source: https://habr.com/ru/post/1242293/


All Articles