ジャクソン - コレクション/配列へのアンマーシャル

ジャクソン–コレクション/配列へのアンマーシャル

1. 概要

このチュートリアルでは、deserialize a JSON Array to a Java Array or Collection with Jackson 2を実行する方法を示します。

さらに深く掘り下げてother cool things you can do with the Jackson 2を学びたい場合は、the main Jackson tutorialに進んでください。

2. アレイへのアンマーシャル

ジャクソンは、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. コレクションへのアンマーシャル

同じJSON配列をJavaコレクションに読み込むのは少し難しいです。デフォルトではJackson will not be able to get the full generic type informationであり、代わりに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));
}

help Jackson understand the right type informationには2つの方法があります。ライブラリによって提供されるTypeReferenceをこの目的に使用することができます。

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

または、JavaTypeを受け入れるオーバーロードされたreadValueメソッドを使用できます。

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

最後の注意点として、MyDtoクラスには引数なしのデフォルトコンストラクタが必要です。そうでない場合は、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. 結論

JSON配列をJavaコレクションにマッピングすることは、Jacksonが使用される最も一般的なタスクの1つであり、これらのソリューションはare vital to getting to a correct, type-safe mappingです。

これらすべての例とコードスニペットcan be found in our GitHub projectの実装–これはMavenベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。