2

Jackson databind v2.9.4. Object mapper definition:

    ObjectMapper objectMapper = new ObjectMapper();

    /*
     * Custom configuration
     */
    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    /*
     * Register mixins
     */
    objectMapper.addMixIn(StackTraceElement.class, StackTraceElementMixin.class);
    objectMapper.addMixIn(Collections.unmodifiableSet(Collections.EMPTY_SET).getClass(), UnmodifiableSetMixin.class);
    // Empty list implements RandomAccess
    objectMapper.addMixIn(Collections.unmodifiableList(Collections.EMPTY_LIST).getClass(), UnmodifiableListMixin.class);

The following test fails with exception: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.Long out of START_ARRAY token at [Source: (String)"{"@class":"java.util.HashMap","1":["java.lang.Long",2]}"; line: 1, column: 35] (through reference chain: java.util.HashMap["1"])

@Test
public void testMapLong() throws IOException {
    Map<Long, Long> hashMap = new HashMap<>();
    hashMap.put(1L, 2L);
    String result = objectMapper.writeValueAsString(hashMap);
    System.out.println(result);
    Map<Long, Long> r = objectMapper.readValue(result, new TypeReference<Map<Long, Long>>(){});
    System.out.print(r.keySet().iterator().next().getClass());

}

The following test works.

@Test
public void testMapInt() throws IOException {
    Map<Integer, Integer> hashMap = new HashMap<>();
    hashMap.put(1, 2);
    String result = objectMapper.writeValueAsString(hashMap);
    System.out.println(result);
    Map<Integer, Integer> r = objectMapper.readValue(result, new TypeReference<Map<Integer, Integer>>(){});
    System.out.print(r.keySet().iterator().next().getClass());

}

This test case works fine:

@Test
public void testSetOfLongUnwrapped() throws IOException {
    Set<Long> hashSet = new HashSet<>();
    hashSet.add(1L);
    hashSet.add(2L);
    String json = objectMapper.writer().forType(objectMapper.getTypeFactory().constructCollectionType(Set.class, Long.class)).writeValueAsString(hashSet);
    Set<Long> pHashSet = objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(Set.class, Long.class));
    Assert.assertEquals(hashSet, pHashSet);
}
SRH LABS
  • 373
  • 1
  • 2
  • 15

0 Answers0