最新Hi
我需要使用RxJava2将CSV文件的内容转换为由Java类映射的JSON。例如,CSV如下所示:
1,John,Smith用户类包括以下属性
Long id;
String name;
String surname;不过,我不是RxJava2的专家,但我正在尝试以下几点:
vertx.fileSystem().rxReadFile("/home/user/file.csv")
.map(buffer -> buffer.toString("UTF-8"))
.map(n -> n.replace(","," "))
.map(JsonObject::new)
.map(json -> json.mapTo(User.class))
.subscribe(
content -> System.out.println("Content: " + content),
err -> System.out.println("Cannot read the file: " + err.getMessage())
);然而,我似乎走错了轨道:
Failed to decode: Cannot deserialize instance of `java.util.LinkedHashMap` out of VALUE_NUMBER_INT token知道如何使用RxJava2转换来实现它吗?谢谢
发布于 2019-10-02 12:13:59
你看这个完全错了。CSV和JSON之间没有自动/神奇的转换。如果您想从您提供的CSV中生成用户对象,可以使用以下代码:
vertx.fileSystem().rxReadFile("/home/lbulic/file.csv")
.map(buffer -> buffer.toString("UTF-8"))
.map(n -> n.split(","))
.map(data -> new User(Long.parseLong(data[0]), data[1], data[2]))
.subscribe(content -> System.out.println("Content: " + content),
err -> System.out.println("Cannot read the file: " + err.getMessage()));您将需要用户对象的构造函数和toString方法才能正确地执行此操作。如果您想要一个JSON而不是用户对象,那么简单的方法就是使用Jackson将生成的用户对象转换为JSON。
rtx.fileSystem().rxReadFile("/home/lbulic/file.csv")
.map(buffer -> buffer.toString("UTF-8"))
.map(n -> n.split(","))
.map(data -> new User(Long.parseLong(data[0]), data[1], data[2]))
.map(user -> Json.encode(user))
.subscribe(content -> System.out.println("Content: " + content),
err -> System.out.println("Cannot read the file: " + err.getMessage()));为此,您还需要用户对象的getter和setter。
如果希望从CSV直接转换为JSON,则需要将CSV的当前结构更改为类似的结构,并需要包含附加依赖项。
CSV:
id,name,surname
1,John,Smith受抚养人:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
<version>2.9.9</version>
</dependency>代码:
CsvSchema csvSchema = CsvSchema.builder().setUseHeader(true).build();
CsvMapper csvMapper = new CsvMapper();
vertx.fileSystem().rxReadFile("/home/lbulic/file.csv")
.map(buffer -> buffer.toString("UTF-8"))
.map(input -> csvMapper.readerFor(Map.class).with(csvSchema).readValues(input).readAll())
.map(list -> list.stream().map(Json::encode).collect(Collectors.toList()))
.subscribe(users -> {
users.forEach(System.out::println);
}, err -> System.out.println("Cannot read the file: " + err.getMessage()));https://stackoverflow.com/questions/58198267
复制相似问题