JSON Item Readers And Writers

Spring Batch 提供了在以下格式中读取和写入 JSON 资源的支持:

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

假定 JSON 资源是一个与各个项目相对应的 JSON 对象的数组。Spring Batch 并不与任何特定的 JSON 库捆绑在一起。

JsonItemReader

JsonItemReader 将 JSON 解析和绑定委托给 org.springframework.batch.item.json.JsonObjectReader 接口的实现。此接口旨在通过一个流式 API 来实现以块的形式读取 JSON 对象。当前提供了两种实现:

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

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

要能够处理 JSON 记录,需要以下内容:

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

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

以下示例展示了如何定义一个使用以前 JSON 资源 org/springframework/batch/item/json/trades.json 和基于 Jackson 的 JsonObjectReaderJsonItemReader

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

JsonFileItemWriter

JsonFileItemWriter 将项目编组委派给 org.springframework.batch.item.json.JsonObjectMarshaller 接口。此接口的契约是要获取一个对象并将它编组为一个 JSON 字符串。当前提供了两种实现:

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

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

要能够写入 JSON 记录,需要以下内容:

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

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

以下示例展示了如何定义一个 JsonFileItemWriter

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