【问题标题】:read complex json file with spring batch用spring批处理读取复杂的json文件
【发布时间】:2015-02-17 14:19:54
【问题描述】:

我有一个复杂的 json 文件(带有嵌套的 json 数组)结构,如下所示:

{"persons":[ 
{"id":"1", "firstName": "X", "lastName": "X", "infos": [{"address":[{"city": "X", "country": "X"}]}]},
{"id":"2", "firstName": "Y", "lastName": "Y", "infos": [{"address":[{"city": "Y", "country": "Y"}]}]}
]}

我想单独阅读每一行(一个人)

所以我的spring批处理配置是这样的

<bean id="reader" class="org.springframework.batch.item.file.FlatFileItemReader"
    scope="step">
    <property name="resource" value="#{jobParameters[file]}" />
    <property name="recordSeparatorPolicy" ref="recordPolicy" />
    <property name="lineMapper" ref="lineMapper" />
</bean>

<bean id="lineMapper"
    class="com.batchs.personJob.PersonLineMapper">
    <property name="delegate" ref="lineMapperType" />
</bean>

<bean id="lineMapperType"
    class="org.springframework.batch.item.file.mapping.JsonLineMapper" />

<bean id="recordPolicy"
    class="org.springframework.batch.item.file.separator.JsonRecordSeparatorPolicy" />

映射器类看起来像

    public class PersonLineMapper implements LineMapper<Person> {
    private JsonLineMapper delegate;

    public mapLine(String line, int lineNumber) throws Exception {
        Map<String, Object> personAsMap = delegate.mapLine(line, lineNumber);
        Person person = new Person();
        // map fields
        return person ;
    }

    public void setDelegate(JsonLineMapper delegate) {
        this.delegate = delegate;
    }
}

问题在于读者只读取一行(所以一次提交),因为他像一整行一样读取我的 json 文件中的人员数组,但我希望每行读取一行(一次一个人)

如何做到这一点?

我尝试过使用这样的简单 json 文件:

  { "id": "1",
      "firstName": "X",
      "lastName": "X"}
  { "id": "2",
      "firstName": "Y",
      "lastName": "Y"}

而且效果很好……我一个一个地读了每个人

非常感谢

【问题讨论】:

    标签: java json spring spring-batch


    【解决方案1】:

    很遗憾,您有两种选择:

    1. 编写您自己的记录分隔符,忽略包装人员元素/行。
    2. 在读取文件之前先在一个步骤中编辑文件,以使用类似 sed 命令的方式删除该包装行。

    如果您选择选项 2,您可以在实际处理它之前的步骤中通过SystemCommandTasklet 执行它。

    【讨论】:

    • 非常感谢,我会尝试第一个选项并返回结果(因为我无法修改文件)。我应该使用默认的 RecordSeparatorPolicy 接口还是 JsonRecordSeparatorPolicy 类?谢谢
    • 非常感谢,第一个解决方案有效。即使我做了一些临时工作,我也设法忽略了文件的开头和结尾,因为不幸的是 JsonRecordSeparatorPolicy 无法自己处理 json 数组
    • ulquiorra能不能分享一下解决办法
    【解决方案2】:

    另一种方法是通过转换步骤运行文件以展平对象结构,这样您只需处理一个 People 数组。这应该没问题,除非您正在处理大文件。

    【讨论】:

    • 感谢您的帮助。这个解决方案也有效(我试过了),但我更喜欢使用记录分隔符,因为我的文件非常大(该步骤需要很长时间才能继续)
    猜你喜欢
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    相关资源
    最近更新 更多