Reputation: 591
Recently been experimenting generating JSON in a streaming way by using JsonGenerator
. Even if you don't link the OutputStream
to your direct output for reading the content you can just read the whole content at the end if you wish.
I'm trying to replicate the exact same thing with Jackson and it's CSV library.
ObjectWriter writer = csvMapper.writer(builder.setUseHeader(true).build());
items.forEachRemaining(item ->
{
// ... prepare item for writing its formatted line to 'writer'
}
);
return ???;
So basically what I'm wondering is, is there any way to collect the whole content from CsvMapper
? Been lurking through the API and couldn't find any method to access any stream or whatever.
Upvotes: 0
Views: 4044
Reputation: 1124
I'd use stream of root node elements and map each element to csv formatted sting. Something like below:
package example;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import com.google.common.collect.Streams;
import org.junit.Test;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
public class CsvMapperTest {
@Test
public void csvMapper() throws Exception{
String [][] names = {
{"1", "John", "Lennon"},
{"2", "Bob", "Marley"}
};
JsonNode jsonNode = new ObjectMapper().valueToTree(names);
CsvSchema s = CsvSchema.builder()
.addColumn("id", CsvSchema.ColumnType.NUMBER_OR_STRING)
.addColumn("name", CsvSchema.ColumnType.STRING)
.addColumn("lastname", CsvSchema.ColumnType.STRING)
.build();
ObjectWriter csvWriter = new CsvMapper().writer(s);
Stream<String> csvStream = Streams.stream(jsonNode.elements()).map(el -> {
try {
return csvWriter.writeValueAsString(el);
} catch (Exception ex) {
return null;
}
}
);
List<String> lines =csvStream.collect(Collectors.toList());
assertThat(lines, hasSize(2));
String line0 = lines.get(0).trim();
assertThat(lines.get(0).trim(), equalTo("1,John,Lennon"));
}
}
Upvotes: 0