Jackson - Marshall String para JsonNode

Jackson - Marshall String para JsonNode

1. Visão geral

Este tutorial rápido mostrará comouse Jackson 2 to convert a JSON String to a JsonNode (com.fasterxml.jackson.databind.JsonNode).

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

2. Análise Rápida

De forma muito simples, para analisar a string JSON, precisamos apenas de umObjectMapper:

@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. Análise de baixo nível

Se, por algum motivo, vocêneed to go lower level do que isso, o exemplo a seguir expõe osJsonParser responsáveis ​​pela análise real da String:

@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. Usando oJsonNode

Depois que o JSON é analisado em um objeto JsonNode, podemoswork 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. Conclusão

Este artigo ilustrouhow to parse JSON Strings into the Jackson JsonNode model para permitir um processamento estruturado do objeto JSON.

A implementação de todos esses exemplos e fragmentos de códigocan be found in my github project - este é um projeto baseado no Eclipse, portanto, deve ser fácil de importar e executar como está.