2

I am trying to read file from classpath in a reactive way using spring webflux. I am able to read the file. But I am not able to parse into an Foo object.

I am trying the following way, but not sure how to convert to an FOO class.

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());
    }

Help appreciated.

sub
  • 527
  • 1
  • 7
  • 24

2 Answers2

0

I think you are doing it correctly but you unfortunately must cast the Object back into the correct type. This is safe to do because the JSON decoding will fail if it was unable to construct a list of 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);
}
Rupert Madden-Abbott
  • 12,899
  • 14
  • 59
  • 74
-1

You can use jackson ObjectMapper:

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

And before that, you should read the file and use FileReader and readLines() to parse line by line.

[UPDATE] Ok, for reading file, reactive means, reading file in a stream, and whenever a line is read, process this line. From this point, the BufferReader.readLines will be fine. But if you really want to use reactive way, you can use:

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();
        }
    }
}
Adam Michalik
  • 9,678
  • 13
  • 71
  • 102
Mavlarn
  • 3,807
  • 2
  • 37
  • 57