我试图使用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());
}
帮助赞赏。
我认为您这样做是正确的,但不幸的是,您必须将Object转换回正确的类型。这是安全的,因为如果JSON解码无法构造Foo
的列表,它将失败:
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);
}
您可以使用杰克逊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();
}
}
}