Jackson - Unmarshall para Coleção/Matriz

Jackson - Unmarshall para Coleção / Matriz

1. Visão geral

Este tutorial mostrará comodeserialize a JSON Array to a Java Array or Collection with Jackson 2.

Se você quiser se aprofundar e aprenderother cool things you can do with the Jackson 2, vá parathe main Jackson tutorial.

2. Desmarcar para Array

Jackson pode facilmente desserializar para uma matriz Java:

@Test
public void givenJsonArray_whenDeserializingAsArray_thenCorrect()
  throws JsonParseException, JsonMappingException, IOException {

    ObjectMapper mapper = new ObjectMapper();
    List 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. Desmarcar para a coleção

Ler o mesmo array JSON em uma coleção Java é um pouco mais difícil - por padrão,Jackson will not be able to get the full generic type information e, em vez disso, criará uma coleção de instâncias LinkedHashMap:

@Test
public void givenJsonArray_whenDeserializingAsListWithNoTypeInfo_thenNotCorrect()
  throws JsonParseException, JsonMappingException, IOException {

    ObjectMapper mapper = new ObjectMapper();

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

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

Existem duas maneiras dehelp Jackson understand the right type information - podemos usar oTypeReference fornecido pela biblioteca para este propósito:

@Test
public void givenJsonArray_whenDeserializingAsListWithTypeReferenceHelp_thenCorrect()
  throws JsonParseException, JsonMappingException, IOException {

    ObjectMapper mapper = new ObjectMapper();

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

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

Ou podemos usar o métodoreadValue sobrecarregado que aceita umJavaType:

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

    List 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 asList = mapper.readValue(jsonArray, javaType);

    assertThat(asList.get(0), instanceOf(MyDto.class));
}

Uma observação final é que a classeMyDto precisa ter o construtor padrão no-args - se não tiver,Jackson will not be able to instantiate it:

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

4. Conclusão

Mapear matrizes JSON para coleções java é uma das tarefas mais comuns para as quais Jackson é usado, e essas soluçõesare vital to getting to a correct, type-safe mapping.

A implementação de todos esses exemplos e trechos de códigocan be found in our GitHub project - este é um projeto baseado em Maven, portanto, deve ser fácil de importar e executar como está.