杰克逊反序列化java.lang.Long泛型类型,启用默认类型失败

时间:2018-03-25 15:55:01

标签: jackson objectmapper jackson-databind

Jackson databind v2.9.4。 对象映射器定义:

    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);

以下测试失败,异常:com.fasterxml.jackson.databind.exc.MismatchedInputException:无法从START_ARRAY标记中反序列化java.lang.Long的实例  at [Source:(String)" {" @ class":" java.util.HashMap"," 1":[" java .lang.Long",2]}&#34 ;; line:1,column:35](通过引用链: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());

}

以下测试有效。

@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());

}

此测试用例正常:

@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);
}

0 个答案:

没有答案