Spring Batch: How to setup a FlatFileItemReader to read a json file?

前端 未结 3 1981
走了就别回头了
走了就别回头了 2020-12-20 03:42

My approach so far:

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


        
3条回答
  •  醉酒成梦
    2020-12-20 04:24

    How to setup a FlatFileItemReader to read a json file?

    It depends on the format of your json file:

    1. Each line is a json object (known as NDJson)

    For example:

    {object1}
    {object2}
    

    then you have two options:

    • 1.1 Use the JsonLineMapper which returns a Map. In this case, your reader should also return Map and you can use an item processor to transform items from Map 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 based on Jackson or Gson or any other library (as shown in the answer by @clevertension)

    2. Lines are wrapped in a json array

    For example:

    [
     {object1},
     {object2}
    ]
    

    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?

提交回复
热议问题