1

I'm trying to deserialize a Java object from JSON, and I usually have no problems, except when the JSON string contains the following field (serialized by JAXB on server side)

"portsOrdered":{"entry":[{"key":"1022016","value":0}]}

I'm trying to bind it to a Map inside my Item object that contains a Map<String, Integer> private field. I do the deserialization with the Spring code

ResponseEntity<Item[]> responseEntity = restTemplate.exchange(context.getBaseUrl(), HttpMethod.POST, 
                    new HttpEntity<Query>(query, context.getDefaultHeaders()), Item[].class);

but I always get the Exception

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of int out of START_ARRAY token
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of int out of START_ARRAY token

Any ideas on how to solve this?

Xstian
  • 8,184
  • 10
  • 42
  • 72
splinter123
  • 1,183
  • 1
  • 14
  • 34

1 Answers1

0

I had the same problem and fortunately found the solution.

The problem occurs because the fetched data is actually a list. If you wrap it, as below, it'll work, but of course, that's not comfortable to use.

private List<HashMap<String, String>> entries = new ArrayList<>();

If you wish to have a simple map in the end you can generate it as follows:

public HashMap<String, String> getEntriesMap() {
   // https://bugs.openjdk.java.net/browse/JDK-8148463 - null values crash.
   // return entries.stream().collect(Collectors.toMap(s -> s.get("id"), s -> s.get("defaultValue")));
   // work around for null values:
   return entries.stream().collect(HashMap::new, (m, v) -> m.put(v.get("id"), v.get("defaultValue")), HashMap::putAll);
}
devaga
  • 326
  • 2
  • 15