java—如何使用flux将json pojo写入csv

y0u0uwnf  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(355)

下面的函数将检索字符串列表。在合并过程中,我想将输出写入csv文件,而不是打印输出。

List<Mono<Device>> list1 = page.get().map(device -> webClient.post()
                .uri(uri)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
                .body(Mono.just("{ \"mac\": \"" + device.getData()  ), String.class)
                .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId("xxxx"))
                .retrieve()
                .bodyToMono(Device.class)).collect(Collectors.toList());

        Flux<Device> mergedMonos = Flux.fromIterable(list1).flatMapSequential(Function.identity());
        mergedMonos.doOnNext(System.out::println)
                .subscribe();

public class Device {
 @JsonProperty("ip")
 private String ip;
 @JsonProperty("macAddress")
 private String macAddress;
 @JsonProperty("vendor")
 private String vendor;

如何将设备(json)数据写入csv文件?
谢谢您

aoyhnmkz

aoyhnmkz1#

在java中将json转换为csv的 checkout
您可以利用jackson库将java对象转换为csv。在依赖项中添加:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-csv</artifactId>
    <version>2.11.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.1</version>
</dependency>

然后在代码中:

ObjectMapper mapper = new ObjectMapper();
Flux<Device> mergedMonos = 
Flux.fromIterable(list1).flatMapSequential(Function.identity());
List<JsonNode> nodes = mergedMonos
    .collectList()
    .map(mapper::valueToTree)
    .subscribe(list -> {
        Builder csvSchemaBuilder = CsvSchema.builder();
        JsonNode firstObject = list.elements().next();
        firstObject.fieldNames().forEachRemaining(fieldName -> {csvSchemaBuilder.addColumn(fieldName);} );
        CsvSchema csvSchema = csvSchemaBuilder.build().withHeader();
        CsvMapper csvMapper = new CsvMapper();
        csvMapper.writerFor(JsonNode.class)
          .with(csvSchema)
          .writeValue(new File("output.csv"), list);
    });

相关问题