Jackson – Unmarshall to Collection/Array – Jackson – 不允许对集合/阵列进行任何操作

最后修改: 2013年 12月 23日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This tutorial will show how to deserialize a JSON Array to a Java Array or Collection with Jackson 2.

本教程将展示如何使用Jackson 2将JSON数组反序列化为一个Java数组或集合。

If you want to dig deeper and learn other cool things you can do with the Jackson 2 – head on over to the main Jackson tutorial.

如果你想深入了解并学习你可以用Jackson 2做的其他很酷的事情–请到Jackson的主要教程

2. Unmarshall to Array

2.无名氏到阵列

Jackson can easily deserialize to a Java Array:

Jackson可以很容易地反序列化为一个Java数组。

@Test
public void givenJsonArray_whenDeserializingAsArray_thenCorrect() 
  throws JsonParseException, JsonMappingException, IOException {
 
    ObjectMapper mapper = new ObjectMapper();
    List<MyDto> listOfDtos = Lists.newArrayList(
      new MyDto("a", 1, true), new MyDto("bc", 3, false));
    String jsonArray = mapper.writeValueAsString(listOfDtos);
 
    // [{"stringValue":"a","intValue":1,"booleanValue":true},
    // {"stringValue":"bc","intValue":3,"booleanValue":false}]

    MyDto[] asArray = mapper.readValue(jsonArray, MyDto[].class);
    assertThat(asArray[0], instanceOf(MyDto.class));
}

3. Unmarshall to Collection

3.无名氏转为收藏

Reading the same JSON Array into a Java Collection is a bit more difficult – by default, Jackson will not be able to get the full generic type information and will instead create a collection of LinkedHashMap instances:

将相同的JSON数组读取到Java集合中就有点困难了–默认情况下,Jackson将无法获得完整的通用类型信息,而是会创建一个LinkedHashMap实例的集合。

@Test
public void givenJsonArray_whenDeserializingAsListWithNoTypeInfo_thenNotCorrect() 
  throws JsonParseException, JsonMappingException, IOException {
 
    ObjectMapper mapper = new ObjectMapper();

    List<MyDto> listOfDtos = Lists.newArrayList(
      new MyDto("a", 1, true), new MyDto("bc", 3, false));
    String jsonArray = mapper.writeValueAsString(listOfDtos);

    List<MyDto> asList = mapper.readValue(jsonArray, List.class);
    assertThat((Object) asList.get(0), instanceOf(LinkedHashMap.class));
}

There are two ways to help Jackson understand the right type information – we can either use the TypeReference provided by the library for this very purpose:

有两种方法可以帮助Jackson理解正确的类型信息–我们可以使用库中提供的TypeReference来达到这个目的。

@Test
public void givenJsonArray_whenDeserializingAsListWithTypeReferenceHelp_thenCorrect() 
  throws JsonParseException, JsonMappingException, IOException {
 
    ObjectMapper mapper = new ObjectMapper();

    List<MyDto> listOfDtos = Lists.newArrayList(
      new MyDto("a", 1, true), new MyDto("bc", 3, false));
    String jsonArray = mapper.writeValueAsString(listOfDtos);

    List<MyDto> asList = mapper.readValue(
      jsonArray, new TypeReference<List<MyDto>>() { });
    assertThat(asList.get(0), instanceOf(MyDto.class));
}

Or we can use the overloaded readValue method that accepts a JavaType:

或者我们可以使用重载的readValue方法,该方法接受一个JavaType

@Test
public void givenJsonArray_whenDeserializingAsListWithJavaTypeHelp_thenCorrect() 
  throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();

    List<MyDto> listOfDtos = Lists.newArrayList(
      new MyDto("a", 1, true), new MyDto("bc", 3, false));
    String jsonArray = mapper.writeValueAsString(listOfDtos);

    CollectionType javaType = mapper.getTypeFactory()
      .constructCollectionType(List.class, MyDto.class);
    List<MyDto> asList = mapper.readValue(jsonArray, javaType);
 
    assertThat(asList.get(0), instanceOf(MyDto.class));
}

One final note is that the MyDto class needs to have the no-args default constructor – if it doesn’t, Jackson will not be able to instantiate it:

最后一点是,MyDto类需要有no-args默认构造函数–如果没有,Jackson将无法实例化它

com.fasterxml.jackson.databind.JsonMappingException: 
No suitable constructor found for type [simple type, class org.baeldung.jackson.ignore.MyDto]: 
can not instantiate from JSON object (need to add/enable type information?)

4. Conclusion

4.结论

Mapping JSON arrays to java collections is one of the more common tasks that Jackson is used for, and these solutions are vital to getting to a correct, type-safe mapping.

将JSON数组映射到java集合是Jackson比较常用的任务之一,而这些解决方案对于获得正确的、类型安全的映射至关重要

The implementation of all these examples and code snippets can be found in our GitHub project – this is a Maven-based project, so it should be easy to import and run as it is.

所有这些例子和代码片段的实现都可以在我们的 GitHub项目中找到 – 这是一个基于Maven的项目,所以应该很容易导入并按原样运行。