How to read and write JSON data with Jackson Core?

Java Conceptuel Diagram

How to read and write JSON data with Jackson Core?

About

This tutorial shows you how to read and write a JSON data structure with the core package of the Jackson Java serialization library.

The core package is the package that manages all basic serialization and deserialization operations at a low level.

The higher-level package in Jackson that permits to instantiate objects is jackson-databind.

Steps

Dependencies

Add the library as a dependency.

Example with Gradle

implementation 'com.fasterxml.jackson.core:jackson-core:2.10.1'

JsonFactory

Creation of a reusable (and thread-safe, once configured) JsonFactory instance

JsonFactory factory = new JsonFactory();
// configure, if necessary:
factory.enable(JsonParser.Feature.ALLOW_COMMENTS);

It can also be done with the jackson-databind library.

JsonFactory factory = objectMapper.getFactory();

Reading / Parsing

All reading is done using JsonParser (or its sub-classes, in case of data formats other than JSON), an instance of which is constructed by JsonFactory.

The Input file is:

{
  "id":4985773666,
  "text":"You need to add it as your \"Favourite\"",
}

The code to parse this Json file with JsonParser:

JsonFactory jsonFactory = new JsonFactory();
Path path = Paths.get("src", "test", "resources", "db-fs", "json");
Path jsonFile = path.resolve("file.json");
JsonParser jsonParser = jsonFactory.createParser(jsonFile.toFile());

// Sanity check: verify that we got "Json Object":
if (jsonParser.nextToken() != JsonToken.START_OBJECT) {
  throw new IOException("Expected data to start with an Object");
}

// Iterate over object fields:
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
  String fieldName = jsonParser.getCurrentName();
  // Let's move to value
  jsonParser.nextToken();
  switch (fieldName) {
	case "id":
	  System.out.println("Id: " + jsonParser.getLongValue());
	  break;
	case "text":
	  System.out.println("Text: " + jsonParser.getText());
	  break;
	default:
	  throw new IOException("Unrecognized field '" + fieldName + "'");
  }
}

jsonParser.close(); // important to close both parser and underlying File reader
  • Output:
Id: 4985773666
Text: You need to add it as your "Favourite"

Writing

JsonFactory jsonFactory = new JsonFactory();
Path jsonFile = Files.createTempFile("write", ".json");
JsonGenerator jsonGenerator = jsonFactory.createGenerator(jsonFile.toFile(), JsonEncoding.UTF8);
jsonGenerator.useDefaultPrettyPrinter(); // enable indentation

jsonGenerator.writeStartObject();
jsonGenerator.writeNumberField("id", 1223);
jsonGenerator.writeStringField("text", "a text");
jsonGenerator.writeEndObject();
jsonGenerator.close();

System.out.println(new String(Files.readAllBytes(jsonFile)));

Output:

{
  "id" : 1223,
  "text" : "a text"
}

1) 2)







Share this page:
Follow us:
Task Runner