[已更新]
嗨
我需要使用 RxJava2 将 CSV 文件的内容转换为由 Java 类映射的 JSON。例如,CSV 如下所示:
1,John,Smith
User Java 类包含属性
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 转换来实现它吗? 谢谢
最佳答案
您对这个问题的看法完全错误。 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()));
您将需要 User 对象的构造函数以及 toString 方法才能正确执行此操作。 如果您想要 JSON 而不是 User 对象,那么简单的方法就是使用 Jackson 将生成的 User 对象转换为 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()));
为此,您还需要 User 对象的 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()));
关于java - 使用 RxJava2 将 CSV 文件转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58198267/