ジャクソン - マーシャルストリングからJsonNodeへ

ジャクソン– JsonNodeへのマーシャル文字列

1. 概要

このクイックチュートリアルでは、use Jackson 2 to convert a JSON String to a JsonNodecom.fasterxml.jackson.databind.JsonNode)の方法を説明します。

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

2. クイック解析

非常に簡単に言えば、JSON文字列を解析するには、ObjectMapperのみが必要です。

@Test
public void whenParsingJsonStringIntoJsonNode_thenCorrect()
  throws JsonParseException, IOException {
    String jsonString = "{"k1":"v1","k2":"v2"}";

    ObjectMapper mapper = new ObjectMapper();
    JsonNode actualObj = mapper.readTree(jsonString);

    assertNotNull(actualObj);
}

3. 低レベルの解析

何らかの理由でそれよりもneed to go lower levelの場合、次の例では、文字列の実際の解析を担当するJsonParserを公開します。

@Test
public void givenUsingLowLevelApi_whenParsingJsonStringIntoJsonNode_thenCorrect()
  throws JsonParseException, IOException {
    String jsonString = "{"k1":"v1","k2":"v2"}";

    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory();
    JsonParser parser = factory.createParser(jsonString);
    JsonNode actualObj = mapper.readTree(parser);

    assertNotNull(actualObj);
}

4. JsonNodeの使用

JSONがJsonNodeオブジェクトに解析された後、work with the Jackson JSON Tree Modelを実行できます。

@Test
public void givenTheJsonNode_whenRetrievingDataFromId_thenCorrect()
  throws JsonParseException, IOException {
    String jsonString = "{"k1":"v1","k2":"v2"}";
    ObjectMapper mapper = new ObjectMapper();
    JsonNode actualObj = mapper.readTree(jsonString);

    // When
    JsonNode jsonNode1 = actualObj.get("k1");
    assertThat(jsonNode1.textValue(), equalTo("v1"));
}

5. 結論

この記事では、JSONオブジェクトの構造化処理を有効にするためのhow to parse JSON Strings into the Jackson JsonNode modelについて説明しました。

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