TedTrippin
TedTrippin

Reputation: 3667

How to deserialise empty array/list?

I have a property

@JsonProperty
private Map<String, String> parameters = new HashMap<String, String>();

When I try to deserialise by calling objectMapper.readValue(...) everything works fine until the parameters field in the JSON is empty, ie.

"parameters":[]

I get this exception...

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.HashMap out of START_ARRAY token

How do I handle empty list? And no I don't have any control over the JSON coming in.

Thanks.

Upvotes: 5

Views: 2566

Answers (2)

StaxMan
StaxMan

Reputation: 116512

As mentioned by Chris, your JSON is wrong.

But if you really need to support this, you can (and need to) create a custom deserializer, and register that for declared Map type -- custom deserializer can then accept arrays (at least empty ones, if those are only kinds that can be encountered).

Upvotes: 0

C. K. Young
C. K. Young

Reputation: 223023

You can only get a HashMap out of {}, not [] (you should be able to get an ArrayList out of it though).

Upvotes: 4

Related Questions