当前版本仍在开发中,尚不被视为稳定版本。最新稳定版请使用 Spring Batch 文档 6.0.2!

JSON ItemReader 与 ItemWriter

Spring Batch 支持读取和写出如下格式的 JSON 资源:

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

这里假定 JSON 资源是一个 JSON 对象数组,其中每个对象都对应一个独立 item。Spring Batch 并不绑定于某一个特定的 JSON 库。

JsonItemReader

JsonItemReader 会把 JSON 的解析与绑定工作委托给 org.springframework.batch.infrastructure.item.json.JsonObjectReader 接口的实现。这个接口旨在通过流式 API 按 chunk 方式读取 JSON 对象。 目前提供了两个实现:

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

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

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

  • Resource:表示待读取 JSON 文件的 Spring Resource。

  • JsonObjectReader:用于解析 JSON 对象并将其绑定为 item 的 JSON 对象读取器。

下面的示例展示了如何定义一个 JsonItemReader,它处理前面提到的 JSON 资源 org/springframework/batch/infrastructure/item/json/trades.json,并使用一个基于 Jackson 的 JsonObjectReader

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

JsonFileItemWriter

JsonFileItemWriter 会把 item 的编组工作委托给 org.springframework.batch.infrastructure.item.json.JsonObjectMarshaller 接口。这个接口的契约是接收一个对象,并将其编组为 JSON String。 目前提供了两个实现:

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

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

要写出 JSON 记录,需要以下内容:

  • Resource:表示待写出 JSON 文件的 Spring Resource

  • JsonObjectMarshaller:用于把对象编组成 JSON 格式的 JSON 对象编组器。

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

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