【问题标题】:How to read JSON file in reactive way using spring webflux?如何使用 spring webflux 以反应方式读取 JSON 文件?
【发布时间】:2021-02-04 20:54:24
【问题描述】:

我正在尝试使用 spring webflux 以反应方式从类路径中读取文件。我能够读取文件。但我无法解析为 Foo 对象。

我正在尝试以下方式,但不确定如何转换为 FOO 类。

public Flux<Object> readFile() {
    Flux<DataBuffer> readFile1 = DataBufferUtils.read("classpath:test.json", new DefaultDataBufferFactory(), 4096);
    return new Jackson2JsonDecoder().decode(readFile1,
        ResolvableType.forType(List.class,Foo.class), null, Collections.emptyMap());
    }

帮助表示赞赏。

【问题讨论】:

  • 您可以将通量转换为单声道,然后是平面映射,然后在字节流上使用对象映射器。

标签: java spring spring-webflux readfile reactive


【解决方案1】:

我认为您做得正确,但不幸的是您必须将 Object 转换回正确的类型。这是安全的,因为如果无法构造Foo 的列表,JSON 解码将失败:

public Flux<Foo> readFile() {
  ResolvableType type = ResolvableType.forType(List.class,Foo.class);
  Flux<DataBuffer> data = DataBufferUtils.read("classpath:test.json", new DefaultDataBufferFactory(), 4096);
    return new Jackson2JsonDecoder().decode(data, type, null, null)
        .map(Foo.class::cast);
}

【讨论】:

    【解决方案2】:

    你可以使用jackson ObjectMapper:

    ObjectMapper mapper = new ObjectMapper();
    Student student = mapper.readValue(jsonString, Student.class);
    

    在此之前,您应该读取文件并使用 FileReader 和 readLines() 逐行解析。

    [更新] 好的,对于读取文件,反应方式,在流中读取文件,并且每当读取一行时,处理这一行。从这一点来看,BufferReader.readLines 就可以了。但是如果你真的想使用响应式的方式,你可以使用:

    package com.test;
    
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.stream.Stream;
    
    public class TestReadFile {
    
        public static void main(String args[]) {
    
            String fileName = "c://lines.txt";
            try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
                stream.forEach(parseLine);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    【讨论】:

    • 会是被动的方式吗?我认为这将是命令式风格
    猜你喜欢
    • 2021-08-11
    • 2020-07-23
    • 2018-02-08
    • 2020-02-25
    • 2018-10-07
    • 2019-04-12
    • 2022-12-19
    • 2019-06-12
    • 2020-04-05
    相关资源
    最近更新 更多