Java - Jackson

Architecture

jackson-core is the low-level incremental (“streaming”) parser and generator abstractions with support out of the box for the JSON format.

The following data format can be plugged into the core:

And therefore, it makes possible to instantiate Java object from all this format with jackson-databind (Java object instantiation)

Tuto / Example - Steps

Dependencies

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

JsonFactory factory = objectMapper.getFactory();

Reading

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

Input file:

{
  "id":4985773666,
  "text":"You need to add it as your \"Favourite\"",
}
  • Code
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"
}

Documentation / Reference


Powered by ComboStrap