For the latest stable version, please use Spring Batch Documentation 5.2.0!

JSON Item Readers And Writers

Spring Batch provides support for reading and Writing JSON resources in the following format:

[
  {
    "isin": "123",
    "quantity": 1,
    "price": 1.2,
    "customer": "foo"
  },
  {
    "isin": "456",
    "quantity": 2,
    "price": 1.4,
    "customer": "bar"
  }
]

It is assumed that the JSON resource is an array of JSON objects corresponding to individual items. Spring Batch is not tied to any particular JSON library.

JsonItemReader

The JsonItemReader delegates JSON parsing and binding to implementations of the org.springframework.batch.item.json.JsonObjectReader interface. This interface is intended to be implemented by using a streaming API to read JSON objects in chunks. Two implementations are currently provided:

  • Jackson through the org.springframework.batch.item.json.JacksonJsonObjectReader

  • Gson through the org.springframework.batch.item.json.GsonJsonObjectReader

To be able to process JSON records, the following is needed:

  • Resource: A Spring Resource that represents the JSON file to read.

  • JsonObjectReader: A JSON object reader to parse and bind JSON objects to items

The following example shows how to define a JsonItemReader that works with the previous JSON resource org/springframework/batch/item/json/trades.json and a JsonObjectReader based on Jackson:

@Bean
public JsonItemReader<Trade> jsonItemReader() {
   return new JsonItemReaderBuilder<Trade>()
                 .jsonObjectReader(new JacksonJsonObjectReader<>(Trade.class))
                 .resource(new ClassPathResource("trades.json"))
                 .name("tradeJsonItemReader")
                 .build();
}

JsonFileItemWriter

The JsonFileItemWriter delegates the marshalling of items to the org.springframework.batch.item.json.JsonObjectMarshaller interface. The contract of this interface is to take an object and marshall it to a JSON String. Two implementations are currently provided:

  • Jackson through the org.springframework.batch.item.json.JacksonJsonObjectMarshaller

  • Gson through the org.springframework.batch.item.json.GsonJsonObjectMarshaller

To be able to write JSON records, the following is needed:

  • Resource: A Spring Resource that represents the JSON file to write

  • JsonObjectMarshaller: A JSON object marshaller to marshall objects to JSON format

The following example shows how to define a JsonFileItemWriter:

@Bean
public JsonFileItemWriter<Trade> jsonFileItemWriter() {
   return new JsonFileItemWriterBuilder<Trade>()
                 .jsonObjectMarshaller(new JacksonJsonObjectMarshaller<>())
                 .resource(new ClassPathResource("trades.json"))
                 .name("tradeJsonFileItemWriter")
                 .build();
}