JSON Item Readers And Writers
Spring Batch 提供了在以下格式中读取和写入 JSON 资源的支持:
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"
}
]
假定 JSON 资源是一个与各个项目相对应的 JSON 对象的数组。Spring Batch 并不与任何特定的 JSON 库捆绑在一起。
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
JsonItemReader
将 JSON 解析和绑定委托给 org.springframework.batch.item.json.JsonObjectReader
接口的实现。此接口旨在通过一个流式 API 来实现以块的形式读取 JSON 对象。当前提供了两种实现:
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:
要能够处理 JSON 记录,需要以下内容:
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
以下示例展示了如何定义一个使用以前 JSON 资源 org/springframework/batch/item/json/trades.json
和基于 Jackson 的 JsonObjectReader
的 JsonItemReader
:
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
JsonFileItemWriter
将项目编组委派给 org.springframework.batch.item.json.JsonObjectMarshaller
接口。此接口的契约是要获取一个对象并将它编组为一个 JSON 字符串。当前提供了两种实现:
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:
要能够写入 JSON 记录,需要以下内容:
To be able to write JSON records, the following is needed:
-
Resource
: A SpringResource
that represents the JSON file to write -
JsonObjectMarshaller
: A JSON object marshaller to marshall objects to JSON format
以下示例展示了如何定义一个 JsonFileItemWriter
:
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();
}