Spring Batch:如何设置FlatFileItemReader来读取json文件? [英] Spring Batch: How to setup a FlatFileItemReader to read a json file?

查看:385
本文介绍了Spring Batch:如何设置FlatFileItemReader来读取json文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止我的方法:

@Bean
FlatFileItemReader<Blub> flatFileItemReader() {
    FlatFileItemReader<Blub> reader = new FlatFileItemReader<>();

    reader.setResource(new FileSystemResource("test.json"));

    JsonLineMapper lineMapper = new JsonLineMapper();

    reader.setLineMapper(lineMapper);

    return reader;
}

挑战是:reader.setLineMapper()无法使用JsonLineMapper.如何正确使用JsonLineMapper?

The challenge is: reader.setLineMapper() cannot use the JsonLineMapper. How to use the JsonLineMapper properly?

推荐答案

如何设置FlatFileItemReader来读取json文件?

How to setup a FlatFileItemReader to read a json file?

这取决于您的json文件的格式:

It depends on the format of your json file:

例如:

{object1}
{object2}

那么您有两个选择:

  • 1.1使用JsonLineMapper返回Map<String, Object>.在这种情况下,您的阅读器还应该返回Map<String, Object>,并且您可以使用项目处理器将项目从Map<String, Object>转换为Blub(顺便说一句,将数据从一种类型转换为另一种类型是项目处理器的典型用例)
  • 1.2使用基于Jackson或Gson或任何其他库的自定义LineMapper<Blub>实现(如@clevertension的答案所示)
  • 1.1 Use the JsonLineMapper which returns a Map<String, Object>. In this case, your reader should also return Map<String, Object> and you can use an item processor to transform items from Map<String, Object> to Blub (BTW, transforming data from one type to another is a typical use case for an item processor)
  • 1.2 Use a custom implementation of LineMapper<Blub> based on Jackson or Gson or any other library (as shown in the answer by @clevertension)

例如:

[
 {object1},
 {object2}
]

然后,您可以使用我们在4.1.0.M1版本中引入的新JsonItemReader(请参见博客文章中的示例,此处为:

then you can use the new JsonItemReader that we introduced in version 4.1.0.M1 (See example in the blog post here: https://spring.io/blog/2018/05/31/spring-batch-4-1-0-m1-released#add-a-new-json-item-reader).

有与此类似的问题,我在这里添加以供参考:

There are similar questions to this one, I'm adding them here for reference:

  • How to read a complex JSON in spring batch?
  • Json Array reader file with spring batch
  • Is there a bug in the new Spring JSON reader or am I doing something wrong?

这篇关于Spring Batch:如何设置FlatFileItemReader来读取json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆