Jackson – Marshall String to JsonNode – Jackson – Marshall String to JsonNode

最后修改: 2013年 12月 23日

1. Overview

1.概述

This quick tutorial will show how to use Jackson 2 to convert a JSON String to a JsonNode (com.fasterxml.jackson.databind.JsonNode).

这个快速教程将展示如何使用Jackson 2将JSON字符串转换为JsonNodecom.fastxml.jackson.databind.JsonNode)。

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.

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

2. Quick Parsing

2.快速解析

Very simply, to parse the JSON String we only need an ObjectMapper:

很简单,要解析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. Low Level Parsing

3.低级别的解析

If, for some reason, you need to go lower level than that, the following example exposes the JsonParser responsible with the actual parsing of the String:

如果出于某种原因,你需要比这更低级别的,下面的例子暴露了负责实际解析String的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. Using the JsonNode

4.使用JsonNode

After the JSON is parsed into a JsonNode Object, we can work with the Jackson JSON Tree Model:

在JSON被解析成JsonNode对象后,我们可以使用Jackson JSON树模型

@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. Conclusion

5.结论

This article illustrated how to parse JSON Strings into the Jackson JsonNode model to enable a structured processing of the JSON Object.

本文说明了如何将JSON字符串解析为Jackson JsonNode模型,以实现JSON对象的结构化处理。

The implementation of all these examples and code snippets can be found in my github project – this is an Eclipse based project, so it should be easy to import and run as it is.

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