Unearthly
Unearthly

Reputation: 169

How to write List<Number> with OpenCSV?

I have the following field inside a StacItem Object:

@JsonProperty
private List<Number> bbox = null;

I made a basic implementation with OpenCSV to write this Object into a CSV, and it mostly works with this code (i'm showing just the relevant part):

final StatefulBeanToCsv<Object> beanToCSV = new StatefulBeanToCsvBuilder<>(writer)
                .withSeparator(';')
                .build();
        for(StacItem item : items){
            beanToCSV.write(item);
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set(HttpHeaders.CONTENT_TYPE, "text/csv");
        httpHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=exportItems.csv");
        logger.info("END WRITING");
        return new ResponseEntity<>(new FileSystemResource(file), HttpStatus.OK);

Here's the twist! In the logs of my Microservice, I see the full structure of that StacItem, and it should have this bbox field:

bbox=[8.24275148213394, 45.5050129344147, 7.62767704092889, 45.0691351737573]

While my implementation returns just this:

"8.24637830863774"

So when I open my CSV I just found the column "bbox" with one value but I need the others too..Can you please tell me why it stops on the first one or how to get the others 3?

UPDATE: I found that this does the trick! But then...it exports just this single field for every StacItem so I lose every other field in my Object.

@CsvBindAndSplitByName(elementType = Number.class, writeDelimiter = ",")
    @JsonProperty("bbox")
    private List<Number> bbox = null;

Thanks

Upvotes: 1

Views: 1082

Answers (2)

Taz
Taz

Reputation: 108

Try using CsvBindByName on every field you want to map (specify the column attribute of the annotation is not mandatory).

You can even use CsvBindByPosition if you prefer.

Upvotes: 1

paranaaan
paranaaan

Reputation: 1736

Did you try to change ?

 beanToCSV.write(item); -> beanToCSV.writeNext(item);

or

    for(StacItem item : items){
        beanToCSV.write(item);
    }

    // to

    beanToCSV.write(items);

Upvotes: 0

Related Questions