JSON Item Readers And Writers

Spring Batch provides support for reading and Writing JSON resources in the following format:spring-doc.cn

[
  {
    "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.spring-doc.cn

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:spring-doc.cn

To be able to process JSON records, the following is needed:spring-doc.cn

  • Resource: A Spring Resource that represents the JSON file to read.spring-doc.cn

  • JsonObjectReader: A JSON object reader to parse and bind JSON objects to itemsspring-doc.cn

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:spring-doc.cn

@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:spring-doc.cn

  • Jackson through the org.springframework.batch.item.json.JacksonJsonObjectMarshallerspring-doc.cn

  • Gson through the org.springframework.batch.item.json.GsonJsonObjectMarshallerspring-doc.cn

To be able to write JSON records, the following is needed:spring-doc.cn

  • Resource: A Spring Resource that represents the JSON file to writespring-doc.cn

  • JsonObjectMarshaller: A JSON object marshaller to marshall objects to JSON formatspring-doc.cn

The following example shows how to define a JsonFileItemWriter:spring-doc.cn

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