Related
Is it possible to specify a schema for the writing part of Jackson with springboot.
For instance:
I have two pojo classes.
class A {
int a;
B b;
public A() { }
// Getter and Setter
}
class B {
double d;
String s;
public B() { }
// Getter and Setter
}
And I have a service
public SomeClass {
#RequestMapping(path = "/mapping", method = RequestMethod.POST)
public A recupererPESRetourDepuisPlateformeBLES()
return callToSomeMethodThatReturnsA();
}
}
Is there a way to specify that for the return type I want:
the attribute a and b of my object A and the attribute s of the object B.
I want the client to somehow send what we want to the server and the server parses the schema required and returns only it.
I know about #JsonIgnore and #JsonProperty.
I also know GraphQL but I want to stay with Jackson.
Update 1
Example:
I have instantiated in Java such a structure (here represented in JSON to simplify)
"A" {
"a": 12,
"b": {
"d": 23.362,
"s": "Hello world"
}
}
After my request, I want the server to send to the client:
"A" {
"a": 12,
"b": {
"s": "Hello world"
}
}
I don't know what kind of data my client can send to my server to specify the schema of data I want as output. This is part of the question.
I assume that you want to be able to do deep filtering ( be able to filter based on properties of classes A and B). To achieve that you can use following filter:
package com.example.demo.filter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.ser.PropertyFilter;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import java.util.Set;
/**
* Sample filtering fields durring json marshalling.
*/
public class JSON {
private static final String DEFAULT_FILTER = "__default";
private static final String DOT = ".";
private static final ObjectMapper MAPPER = new ObjectMapper().setAnnotationIntrospector(
new AnnotationIntrospectorPair(
new FilteringAnnotationInpector(), new JaxbAnnotationIntrospector(TypeFactory.defaultInstance())
)
);
public static String asString(Object object, Set<String> fields) {
PropertyFilter filter = filter(fields);
SimpleFilterProvider provider = new SimpleFilterProvider();
provider.addFilter(DEFAULT_FILTER, filter);
try {
return MAPPER.writer(provider).writeValueAsString(object);
} catch (JsonProcessingException ex) {
throw new RuntimeException("failed to marshall", ex);
}
}
private static PropertyFilter filter(Set<String> fields) {
PropertyFilter filter;
if (fields.size() > 0) {
filter = new DeepFieldFilter(fields);
} else {
filter = SimpleBeanPropertyFilter.serializeAll();
}
return filter;
}
private static class FilteringAnnotationInpector extends JacksonAnnotationIntrospector {
private static final long serialVersionUID = -8722016441050379430L;
#Override
public String findFilterId(Annotated a) {
return DEFAULT_FILTER;
}
}
private static class DeepFieldFilter extends SimpleBeanPropertyFilter {
private final Set<String> includes;
private DeepFieldFilter(Set<String> includes) {
this.includes = includes;
}
private String createPath(PropertyWriter writer, JsonGenerator jgen) {
StringBuilder path = new StringBuilder();
path.append(writer.getName());
JsonStreamContext sc = jgen.getOutputContext();
if (sc != null) {
sc = sc.getParent();
}
while (sc != null) {
if (sc.getCurrentName() != null) {
if (path.length() > 0) {
path.insert(0, DOT);
}
path.insert(0, sc.getCurrentName());
}
sc = sc.getParent();
}
return path.toString();
}
#Override
public void serializeAsField(Object pojo, JsonGenerator gen, SerializerProvider provider, PropertyWriter writer)
throws Exception {
String path = createPath(writer, gen);
if (includes.contains(path)) {
writer.serializeAsField(pojo, gen, provider);
} else {
writer.serializeAsOmittedField(pojo, gen, provider);
}
}
}
}
Here is complete example how to use this.
So, for example, if you want to return only property "a" of object A, first you will create controller method like this:
#GetMapping("/test")
public String test(#RequestBody Set<String> filterFields) {
B b = new B();
b.setD(23);
b.setS("b test");
A a = new A();
a.setA(1);
a.setB(b);
return JSON.asString(a, filterFields);
}
And if you send request like this:
The output should be {"a":1}
If you want to display property b of A class, with field s, you will send request like this:
And the output shoud be {"b":{"s":"b test"}}
As far as I can see, there is no other way to achieve what you want (using just Jackson).
Spring boot dynamic filtering concept should help in this case. Modify the return type of the method recupererPESRetourDepuisPlateformeBLES() to MappingJacksonValue . Here are the code changes needed to be made:
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
public SomeClass {
#RequestMapping(path = "/mapping", method = RequestMethod.POST)
public MappingJacksonValue recupererPESRetourDepuisPlateformeBLES()
SimpleBeanPropertyFilter propertyFilter = SimpleBeanPropertyFilter.filterOutAllExcept("s");
FilterProvider filterProvider = new SimpleFilterProvider().addFilter("dynamicFilter", propertyFilter);
B b = new B();
b.setD(1d);
b.setS("someString");
A a = new A();
a.setA(1);
a.setB(b);
MappingJacksonValue value = new MappingJacksonValue(a);
value.setFilters(filterProvider);
return value;
}
}
Annotate the target Response class with #JsonFilter like below
import com.fasterxml.jackson.annotation.JsonFilter;
#JsonFilter("dynamicFilter")
public class B {
double d;
String s;
public B() {
}
}
Hope. This should solve the problem.
I have created a MappingsBean class where all the columns of the CSV file are specified. Next I parse XML files and create a list of mappingbeans. Then I write that data into CSV file as report.
I am using following annotations:
public class MappingsBean {
#CsvBindByName(column = "TradeID")
#CsvBindByPosition(position = 0)
private String tradeId;
#CsvBindByName(column = "GWML GUID", required = true)
#CsvBindByPosition(position = 1)
private String gwmlGUID;
#CsvBindByName(column = "MXML GUID", required = true)
#CsvBindByPosition(position = 2)
private String mxmlGUID;
#CsvBindByName(column = "GWML File")
#CsvBindByPosition(position = 3)
private String gwmlFile;
#CsvBindByName(column = "MxML File")
#CsvBindByPosition(position = 4)
private String mxmlFile;
#CsvBindByName(column = "MxML Counterparty")
#CsvBindByPosition(position = 5)
private String mxmlCounterParty;
#CsvBindByName(column = "GWML Counterparty")
#CsvBindByPosition(position = 6)
private String gwmlCounterParty;
}
And then I use StatefulBeanToCsv class to write into CSV file:
File reportFile = new File(reportOutputDir + "/" + REPORT_FILENAME);
Writer writer = new PrintWriter(reportFile);
StatefulBeanToCsv<MappingsBean> beanToCsv = new
StatefulBeanToCsvBuilder(writer).build();
beanToCsv.write(makeFinalMappingBeanList());
writer.close();
The problem with this approach is that if I use #CsvBindByPosition(position = 0) to control
position then I am not able to generate column names. If I use #CsvBindByName(column = "TradeID") then I am not able to set position of the columns.
Is there a way where I can use both annotations, so that I can create CSV files with column headers and also control column position?
Regards,
Vikram Pathania
I've had similar problem. AFAIK there is no build-in functionality in OpenCSV that will allow to write bean to CSV with custom column names and ordering.
There are two main MappingStrategyies that are available in OpenCSV out of the box:
HeaderColumnNameMappingStrategy: that allows to map CVS file columns to bean fields based on custom name; when writing bean to CSV this allows to change column header name but we have no control on column order
ColumnPositionMappingStrategy: that allows to map CSV file columns to bean fields based on column ordering; when writing bean to CSV we can control column order but we get an empty header (implementation returns new String[0] as a header)
The only way I found to achieve both custom column names and ordering is to write your custom MappingStrategy.
First solution: fast and easy but hardcoded
Create custom MappingStrategy:
class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
private static final String[] HEADER = new String[]{"TradeID", "GWML GUID", "MXML GUID", "GWML File", "MxML File", "MxML Counterparty", "GWML Counterparty"};
#Override
public String[] generateHeader() {
return HEADER;
}
}
And use it in StatefulBeanToCsvBuilder:
final CustomMappingStrategy<MappingsBean> mappingStrategy = new CustomMappingStrategy<>();
mappingStrategy.setType(MappingsBean.class);
final StatefulBeanToCsv<MappingsBean> beanToCsv = new StatefulBeanToCsvBuilder<MappingsBean>(writer)
.withMappingStrategy(mappingStrategy)
.build();
beanToCsv.write(makeFinalMappingBeanList());
writer.close()
In MappingsBean class we left CsvBindByPosition annotations - to control ordering (in this solution CsvBindByName annotations are not needed). Thanks to custom mapping strategy the header column names are included in resulting CSV file.
The downside of this solution is that when we change column ordering through CsvBindByPosition annotation we have to manually change also HEADER constant in our custom mapping strategy.
Second solution: more flexible
The first solution works, but it was not good for me. Based on build-in implementations of MappingStrategy I came up with yet another implementation:
class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader() {
final int numColumns = findMaxFieldIndex();
if (!isAnnotationDriven() || numColumns == -1) {
return super.generateHeader();
}
header = new String[numColumns + 1];
BeanField beanField;
for (int i = 0; i <= numColumns; i++) {
beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField);
header[i] = columnHeaderName;
}
return header;
}
private String extractHeaderName(final BeanField beanField) {
if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0) {
return StringUtils.EMPTY;
}
final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
}
You can use this custom strategy in StatefulBeanToCsvBuilder exactly this same as in the first solution (remember to invoke mappingStrategy.setType(MappingsBean.class);, otherwise this solution will not work).
Currently our MappingsBean has to contain both CsvBindByName and CsvBindByPosition annotations. The first to give header column name and the second to create ordering of columns in the output CSV header. Now if we change (using annotations) either column name or ordering in MappingsBean class - that change will be reflected in output CSV file.
Corrected above answer to match with newer version.
package csvpojo;
import org.apache.commons.lang3.StringUtils;
import com.opencsv.bean.BeanField;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvBindByName;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
super.setColumnMapping(new String[ FieldUtils.getAllFields(bean.getClass()).length]);
final int numColumns = findMaxFieldIndex();
if (!isAnnotationDriven() || numColumns == -1) {
return super.generateHeader(bean);
}
String[] header = new String[numColumns + 1];
BeanField<T> beanField;
for (int i = 0; i <= numColumns; i++) {
beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField);
header[i] = columnHeaderName;
}
return header;
}
private String extractHeaderName(final BeanField<T> beanField) {
if (beanField == null || beanField.getField() == null
|| beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0) {
return StringUtils.EMPTY;
}
final CsvBindByName bindByNameAnnotation = beanField.getField()
.getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
}
Then call this to generate CSV. I have used Visitors as my POJO to populate, update wherever necessary.
CustomMappingStrategy<Visitors> mappingStrategy = new CustomMappingStrategy<>();
mappingStrategy.setType(Visitors.class);
// writing sample
List<Visitors> beans2 = new ArrayList<Visitors>();
Visitors v = new Visitors();
v.set_1_firstName(" test1");
v.set_2_lastName("lastname1");
v.set_3_visitsToWebsite("876");
beans2.add(v);
v = new Visitors();
v.set_1_firstName(" firstsample2");
v.set_2_lastName("lastname2");
v.set_3_visitsToWebsite("777");
beans2.add(v);
Writer writer = new FileWriter("G://output.csv");
StatefulBeanToCsv<Visitors> beanToCsv = new StatefulBeanToCsvBuilder<Visitors>(writer)
.withMappingStrategy(mappingStrategy).withSeparator(',').withApplyQuotesToAll(false).build();
beanToCsv.write(beans2);
writer.close();
My bean annotations looks like this
#CsvBindByName (column = "First Name", required = true)
#CsvBindByPosition(position=1)
private String firstName;
#CsvBindByName (column = "Last Name", required = true)
#CsvBindByPosition(position=0)
private String lastName;
I wanted to achieve bi-directional import/export - to be able to import generated CSV back to POJO and visa versa.
I was not able to use #CsvBindByPosition for this, because in this case - ColumnPositionMappingStrategy was selected automatically. Per documents: this strategy requires that the file does NOT have a header.
What I've used to achieve the goal:
HeaderColumnNameMappingStrategy
mappingStrategy.setColumnOrderOnWrite(Comparator<String> writeOrder)
CsvUtils to read/write csv
import com.opencsv.CSVWriter;
import com.opencsv.bean.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.List;
public class CsvUtils {
private CsvUtils() {
}
public static <T> String convertToCsv(List<T> entitiesList, MappingStrategy<T> mappingStrategy) throws Exception {
try (Writer writer = new StringWriter()) {
StatefulBeanToCsv<T> beanToCsv = new StatefulBeanToCsvBuilder<T>(writer)
.withMappingStrategy(mappingStrategy)
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.build();
beanToCsv.write(entitiesList);
return writer.toString();
}
}
#SuppressWarnings("unchecked")
public static <T> List<T> convertFromCsv(MultipartFile file, Class clazz) throws IOException {
try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(reader).withType(clazz).build();
return csvToBean.parse();
}
}
}
POJO for import/export
public class LocalBusinessTrainingPairDTO {
//this is used for CSV columns ordering on exporting LocalBusinessTrainingPairs
public static final String[] FIELDS_ORDER = {"leftId", "leftName", "rightId", "rightName"};
#CsvBindByName(column = "leftId")
private int leftId;
#CsvBindByName(column = "leftName")
private String leftName;
#CsvBindByName(column = "rightId")
private int rightId;
#CsvBindByName(column = "rightName")
private String rightName;
// getters/setters omitted, do not forget to add them
}
Custom comparator for predefined String ordering:
public class OrderedComparatorIgnoringCase implements Comparator<String> {
private List<String> predefinedOrder;
public OrderedComparatorIgnoringCase(String[] predefinedOrder) {
this.predefinedOrder = new ArrayList<>();
for (String item : predefinedOrder) {
this.predefinedOrder.add(item.toLowerCase());
}
}
#Override
public int compare(String o1, String o2) {
return predefinedOrder.indexOf(o1.toLowerCase()) - predefinedOrder.indexOf(o2.toLowerCase());
}
}
Ordered writing for POJO (answer to initial question)
public static void main(String[] args) throws Exception {
List<LocalBusinessTrainingPairDTO> localBusinessTrainingPairsDTO = new ArrayList<>();
LocalBusinessTrainingPairDTO localBusinessTrainingPairDTO = new LocalBusinessTrainingPairDTO();
localBusinessTrainingPairDTO.setLeftId(1);
localBusinessTrainingPairDTO.setLeftName("leftName");
localBusinessTrainingPairDTO.setRightId(2);
localBusinessTrainingPairDTO.setRightName("rightName");
localBusinessTrainingPairsDTO.add(localBusinessTrainingPairDTO);
//Creating HeaderColumnNameMappingStrategy
HeaderColumnNameMappingStrategy<LocalBusinessTrainingPairDTO> mappingStrategy = new HeaderColumnNameMappingStrategy<>();
mappingStrategy.setType(LocalBusinessTrainingPairDTO.class);
//Setting predefined order using String comparator
mappingStrategy.setColumnOrderOnWrite(new OrderedComparatorIgnoringCase(LocalBusinessTrainingPairDTO.FIELDS_ORDER));
String csv = convertToCsv(localBusinessTrainingPairsDTO, mappingStrategy);
System.out.println(csv);
}
Read exported CSV back to POJO (addition to original answer)
Important: CSV can be unordered, as we are still using binding by name:
public static void main(String[] args) throws Exception {
//omitted code from writing
String csv = convertToCsv(localBusinessTrainingPairsDTO, mappingStrategy);
//Exported CSV should be compatible for further import
File temp = File.createTempFile("tempTrainingPairs", ".csv");
temp.deleteOnExit();
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
bw.write(csv);
bw.close();
MultipartFile multipartFile = new MockMultipartFile("tempTrainingPairs.csv", new FileInputStream(temp));
List<LocalBusinessTrainingPairDTO> localBusinessTrainingPairDTOList = convertFromCsv(multipartFile, LocalBusinessTrainingPairDTO.class);
}
To conclude:
We can read CSV to POJO, regardless of column order - because we are
using #CsvBindByName
We can control columns order on write using
custom comparator
In the latest version the solution of #Sebast26 does no longer work. However the basic is still very good. Here is a working solution with v5.0
import com.opencsv.bean.BeanField;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvBindByName;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
import org.apache.commons.lang3.StringUtils;
class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
final int numColumns = getFieldMap().values().size();
super.generateHeader(bean);
String[] header = new String[numColumns];
BeanField beanField;
for (int i = 0; i < numColumns; i++) {
beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField);
header[i] = columnHeaderName;
}
return header;
}
private String extractHeaderName(final BeanField beanField) {
if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(
CsvBindByName.class).length == 0) {
return StringUtils.EMPTY;
}
final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
}
And the model looks like this:
#CsvBindByName(column = "id")
#CsvBindByPosition(position = 0)
private Long id;
#CsvBindByName(column = "name")
#CsvBindByPosition(position = 1)
private String name;
And my generation helper looks something like this:
public static <T extends AbstractCsv> String createCsv(List<T> data, Class<T> beanClazz) {
CustomMappingStrategy<T> mappingStrategy = new CustomMappingStrategy<T>();
mappingStrategy.setType(beanClazz);
StringWriter writer = new StringWriter();
String csv = "";
try {
StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(writer)
.withSeparator(';')
.withMappingStrategy(mappingStrategy)
.build();
sbc.write(data);
csv = writer.toString();
} catch (CsvRequiredFieldEmptyException e) {
// TODO add some logging...
} catch (CsvDataTypeMismatchException e) {
// TODO add some logging...
} finally {
try {
writer.close();
} catch (IOException e) {
}
}
return csv;
}
The following works for me to map a POJO to a CSV file with custom column positioning and custom column headers (tested with opencsv-5.0) :
public class CustomBeanToCSVMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
String[] headersAsPerFieldName = getFieldMap().generateHeader(bean); // header name based on field name
String[] header = new String[headersAsPerFieldName.length];
for (int i = 0; i <= headersAsPerFieldName.length - 1; i++) {
BeanField beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField); // header name based on #CsvBindByName annotation
if (columnHeaderName.isEmpty()) // No #CsvBindByName is present
columnHeaderName = headersAsPerFieldName[i]; // defaults to header name based on field name
header[i] = columnHeaderName;
}
headerIndex.initializeHeaderIndex(header);
return header;
}
private String extractHeaderName(final BeanField beanField) {
if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0) {
return StringUtils.EMPTY;
}
final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
}
Pojo
Column Positioning in the generated CSV file:
The column positioing in the generated CSV file will be as per the annotation #CsvBindByPosition
Header name in the generated CSV file:
If the field has #CsvBindByName, the generated header will be as per the annonation
If the field doesn't have #CsvBindByName, then the generated header will be as per the field name
#Getter #Setter #ToString
public class Pojo {
#CsvBindByName(column="Voucher Series") // header: "Voucher Series"
#CsvBindByPosition(position=0)
private String voucherSeries;
#CsvBindByPosition(position=1) // header: "salePurchaseType"
private String salePurchaseType;
}
Using the above Custom Mapping Strategy:
CustomBeanToCSVMappingStrategy<Pojo> mappingStrategy = new CustomBeanToCSVMappingStrategy<>();
mappingStrategy.setType(Pojo.class);
StatefulBeanToCsv<Pojo> beanToCsv = new StatefulBeanToCsvBuilder<Pojo>(writer)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withMappingStrategy(mappingStrategy)
.build();
beanToCsv.write(pojoList);
thanks for this thread, it has been really useful for me... I've enhanced a little bit the provided solution in order to accept also POJO where some fields are not annotated (not meant to be read/written):
public class ColumnAndNameMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
super.setColumnMapping(new String[ getAnnotatedFields(bean)]);
final int numColumns = getAnnotatedFields(bean);
final int totalFieldNum = findMaxFieldIndex();
if (!isAnnotationDriven() || numColumns == -1) {
return super.generateHeader(bean);
}
String[] header = new String[numColumns];
BeanField<T> beanField;
for (int i = 0; i <= totalFieldNum; i++) {
beanField = findField(i);
if (isFieldAnnotated(beanField.getField())) {
String columnHeaderName = extractHeaderName(beanField);
header[i] = columnHeaderName;
}
}
return header;
}
private int getAnnotatedFields(T bean) {
return (int) Arrays.stream(FieldUtils.getAllFields(bean.getClass()))
.filter(this::isFieldAnnotated)
.count();
}
private boolean isFieldAnnotated(Field f) {
return f.isAnnotationPresent(CsvBindByName.class) || f.isAnnotationPresent(CsvCustomBindByName.class);
}
private String extractHeaderName(final BeanField beanField) {
if (beanField == null || beanField.getField() == null) {
return StringUtils.EMPTY;
}
Field field = beanField.getField();
if (field.getDeclaredAnnotationsByType(CsvBindByName.class).length != 0) {
final CsvBindByName bindByNameAnnotation = field.getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
if (field.getDeclaredAnnotationsByType(CsvCustomBindByName.class).length != 0) {
final CsvCustomBindByName bindByNameAnnotation = field.getDeclaredAnnotationsByType(CsvCustomBindByName.class)[0];
return bindByNameAnnotation.column();
}
return StringUtils.EMPTY;
}
}
If you're only interested in sorting the CSV columns based on the order in which member variables appear in your model class (CsvRow row in this example), then you can use a Comparator implementation to solve this in a rather simple manner. Here's an example that does this in Kotlin:
class ByMemberOrderCsvComparator : Comparator<String> {
private val memberOrder by lazy {
FieldUtils.getAllFields(CsvRow::class.java)
.map { it.getDeclaredAnnotation(CsvBindByName::class.java) }
.map { it?.column ?: "" }
.map { it.toUpperCase(Locale.US) } // OpenCSV UpperCases all headers, so we do this to match
}
override fun compare(field1: String?, field2: String?): Int {
return memberOrder.indexOf(field1) - memberOrder.indexOf(field2)
}
}
This Comparator does the following:
Fetches each member variable field in our data class (CsvRow)
Finds all the ones with the #CsvBindByName annotation (in the order you specified them in the CsvRow model)
Upper cases each to match the default OpenCsv implementation
Next, apply this Comparator to your MappingStrategy, so it'll sort based off the specified order:
val mappingStrategy = HeaderColumnNameMappingStrategy<OrderSummaryCsvRow>()
mappingStrategy.setColumnOrderOnWrite(ByMemberOrderCsvComparator())
mappingStrategy.type = CsvRow::class.java
mappingStrategy.setErrorLocale(Locale.US)
val csvWriter = StatefulBeanToCsvBuilder<OrderSummaryCsvRow>(writer)
.withMappingStrategy(mappingStrategy)
.build()
For reference, here's an example CsvRow class (you'll want to replace this with your own model for your needs):
data class CsvRow(
#CsvBindByName(column = "Column 1")
val column1: String,
#CsvBindByName(column = "Column 2")
val column2: String,
#CsvBindByName(column = "Column 3")
val column3: String,
// Other columns here ...
)
Which would produce a CSV as follows:
"COLUMN 1","COLUMN 2","COLUMN 3",...
"value 1a","value 2a","value 3a",...
"value 1b","value 2b","value 3b",...
The benefit of this approach is that it removes the need to hard-code any of your column names, which should greatly simplify things if you ever need to add/remove columns.
It is a solution for version greater than 4.3:
public class MappingBean {
#CsvBindByName(column = "column_a")
private String columnA;
#CsvBindByName(column = "column_b")
private String columnB;
#CsvBindByName(column = "column_c")
private String columnC;
// getters and setters
}
And use it as example:
import org.apache.commons.collections4.comparators.FixedOrderComparator;
...
var mappingStrategy = new HeaderColumnNameMappingStrategy<MappingBean>();
mappingStrategy.setType(MappingBean.class);
mappingStrategy.setColumnOrderOnWrite(new FixedOrderComparator<>("COLUMN_C", "COLUMN_B", "COLUMN_A"));
var sbc = new StatefulBeanToCsvBuilder<MappingBean>(writer)
.withMappingStrategy(mappingStrategy)
.build();
Result:
column_c | column_b | column_a
The following solution works with opencsv 5.0.
First, you need to inherit ColumnPositionMappingStrategy class and override generateHeader method to create your custom header for utilizing both CsvBindByName and CsvBindByPosition annotations as shown below.
import com.opencsv.bean.BeanField;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvBindByName;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
/**
* #param <T>
*/
class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
/*
* (non-Javadoc)
*
* #see com.opencsv.bean.ColumnPositionMappingStrategy#generateHeader(java.lang.
* Object)
*/
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
final int numColumns = getFieldMap().values().size();
if (numColumns == -1) {
return super.generateHeader(bean);
}
String[] header = new String[numColumns];
super.setColumnMapping(header);
BeanField<T, Integer> beanField;
for (int i = 0; i < numColumns; i++) {
beanField = findField(i);
String columnHeaderName = beanField.getField().getDeclaredAnnotation(CsvBindByName.class).column();
header[i] = columnHeaderName;
}
return header;
}
}
The next step is to use this mapping strategy while writing a bean to CSV as below.
CustomMappingStrategy<ScanReport> strategy = new CustomMappingStrategy<>();
strategy.setType(ScanReport.class);
// Write a bean to csv file.
StatefulBeanToCsv<ScanReport> beanToCsv = new StatefulBeanToCsvBuilder<ScanReport>(writer)
.withMappingStrategy(strategy).build();
beanToCsv.write(beanList);
I've improved on previous answers by removing all references to deprecated APIs while using the latest release of opencsv (4.6).
A Generic Kotlin Solution
/**
* Custom OpenCSV [ColumnPositionMappingStrategy] that allows for a header line to be generated from a target CSV
* bean model class using the following annotations when present:
* * [CsvBindByName]
* * [CsvCustomBindByName]
*/
class CustomMappingStrategy<T>(private val beanType: Class<T>) : ColumnPositionMappingStrategy<T>() {
init {
setType(beanType)
setColumnMapping(*getAnnotatedFields().map { it.extractHeaderName() }.toTypedArray())
}
override fun generateHeader(bean: T): Array<String> = columnMapping
private fun getAnnotatedFields() = beanType.declaredFields.filter { it.isAnnotatedByName() }.toList()
private fun Field.isAnnotatedByName() = isAnnotationPresent(CsvBindByName::class.java) || isAnnotationPresent(CsvCustomBindByName::class.java)
private fun Field.extractHeaderName() =
getAnnotation(CsvBindByName::class.java)?.column ?: getAnnotation(CsvCustomBindByName::class.java)?.column ?: EMPTY
}
Then use it as follows:
private fun csvBuilder(writer: Writer) =
StatefulBeanToCsvBuilder<MappingsBean>(writer)
.withSeparator(ICSVWriter.DEFAULT_SEPARATOR)
.withMappingStrategy(CustomMappingStrategy(MappingsBean::class.java))
.withApplyQuotesToAll(false)
.build()
// Kotlin try-with-resources construct
PrintWriter(File("$reportOutputDir/$REPORT_FILENAME")).use { writer ->
csvBuilder(writer).write(makeFinalMappingBeanList())
}
and for completeness, here's the CSV bean as a Kotlin data class:
data class MappingsBean(
#field:CsvBindByName(column = "TradeID")
#field:CsvBindByPosition(position = 0, required = true)
private val tradeId: String,
#field:CsvBindByName(column = "GWML GUID", required = true)
#field:CsvBindByPosition(position = 1)
private val gwmlGUID: String,
#field:CsvBindByName(column = "MXML GUID", required = true)
#field:CsvBindByPosition(position = 2)
private val mxmlGUID: String,
#field:CsvBindByName(column = "GWML File")
#field:CsvBindByPosition(position = 3)
private val gwmlFile: String? = null,
#field:CsvBindByName(column = "MxML File")
#field:CsvBindByPosition(position = 4)
private val mxmlFile: String? = null,
#field:CsvBindByName(column = "MxML Counterparty")
#field:CsvBindByPosition(position = 5)
private val mxmlCounterParty: String? = null,
#field:CsvBindByName(column = "GWML Counterparty")
#field:CsvBindByPosition(position = 6)
private val gwmlCounterParty: String? = null
)
I think the intended and most flexible way of handling the order of the header columns is to inject a comparator by HeaderColumnNameMappinStrategy.setColumnOrderOnWrite().
For me the most intuitive way was to write the CSV columns in the same order as they are specified in the CsvBean, but you can also adjust the Comparator to make use of your own annotations where you specify the order. Don´t forget to rename the Comparator class then ;)
Integration:
HeaderColumnNameMappingStrategy<MyCsvBean> mappingStrategy = new HeaderColumnNameMappingStrategy<>();
mappingStrategy.setType(MyCsvBean.class);
mappingStrategy.setColumnOrderOnWrite(new ClassFieldOrderComparator(MyCsvBean.class));
Comparator:
private class ClassFieldOrderComparator implements Comparator<String> {
List<String> fieldNamesInOrderWithinClass;
public ClassFieldOrderComparator(Class<?> clazz) {
fieldNamesInOrderWithinClass = Arrays.stream(clazz.getDeclaredFields())
.filter(field -> field.getAnnotation(CsvBindByName.class) != null)
// Handle order by your custom annotation here
//.sorted((field1, field2) -> {
// int field1Order = field1.getAnnotation(YourCustomOrderAnnotation.class).getOrder();
// int field2Order = field2.getAnnotation(YourCustomOrderAnnotation.class).getOrder();
// return Integer.compare(field1Order, field2Order);
//})
.map(field -> field.getName().toUpperCase())
.collect(Collectors.toList());
}
#Override
public int compare(String o1, String o2) {
int fieldIndexo1 = fieldNamesInOrderWithinClass.indexOf(o1);
int fieldIndexo2 = fieldNamesInOrderWithinClass.indexOf(o2);
return Integer.compare(fieldIndexo1, fieldIndexo2);
}
}
This can be done using a HeaderColumnNameMappingStrategy along with a custom Comparator as well.
Which is recommended by the official doc http://opencsv.sourceforge.net/#mapping_strategies
File reportFile = new File(reportOutputDir + "/" + REPORT_FILENAME);
Writer writer = new PrintWriter(reportFile);
final List<String> order = List.of("TradeID", "GWML GUID", "MXML GUID", "GWML File", "MxML File", "MxML Counterparty", "GWML Counterparty");
final FixedOrderComparator comparator = new FixedOrderComparator(order);
HeaderColumnNameMappingStrategy<MappingsBean> strategy = new HeaderColumnNameMappingStrategy<>();
strategy.setType(MappingsBean.class);
strategy.setColumnOrderOnWrite(comparator);
StatefulBeanToCsv<MappingsBean> beanToCsv = new
StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(strategy)
.build();
beanToCsv.write(makeFinalMappingBeanList());
writer.close();
CustomMappingStrategy for generic class.
public class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
super.setColumnMapping(new String[ FieldUtils.getAllFields(bean.getClass()).length]);
final int numColumns = findMaxFieldIndex();
if (!isAnnotationDriven() || numColumns == -1) {
return super.generateHeader(bean);
}
String[] header = new String[numColumns + 1];
BeanField<T> beanField;
for (int i = 0; i <= numColumns; i++) {
beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField);
header[i] = columnHeaderName;
}
return header;
}
private String extractHeaderName(final BeanField<T> beanField) {
if (beanField == null || beanField.getField() == null
|| beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0) {
return StringUtils.EMPTY;
}
final CsvBindByName bindByNameAnnotation = beanField.getField()
.getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
}
POJO Class
public class Customer{
#CsvBindByPosition(position=1)
#CsvBindByName(column="CUSTOMER", required = true)
private String customer;
}
Client Class
List<T> data = getEmployeeRecord();
CustomMappingStrategy custom = new CustomMappingStrategy();
custom.setType(Employee.class);
StatefulBeanToCsv<T> writer = new StatefulBeanToCsvBuilder<T>(response.getWriter())
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withSeparator('|')
.withOrderedResults(false)
.withMappingStrategy(custom)
.build();
writer.write(reportData);
There is another version for 5.2 version because I have a problem with #CsvCustomBindByName annotation when I tried answers above.
I defined custom annotation :
#Target(ElementType.FIELD)
#Inherited
#Retention(RetentionPolicy.RUNTIME)
public #interface CsvPosition {
int position();
}
and custom mapping strategy
public class CustomMappingStrategy<T> extends HeaderColumnNameMappingStrategy<T> {
private final Field[] fields;
public CustomMappingStrategy(Class<T> clazz) {
fields = clazz.getDeclaredFields();
Arrays.sort(fields, (f1, f2) -> {
CsvPosition position1 = f1.getAnnotation(CsvPosition.class);
CsvPosition position2 = f2.getAnnotation(CsvPosition.class);
return Integer.compare(position1.position(), position2.position());
});
}
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
String[] header = new String[fields.length];
for (Field f : fields) {
CsvPosition position = f.getAnnotation(CsvPosition.class);
header[position.position() - 1] = getName(f);
}
headerIndex.initializeHeaderIndex(header);
return header;
}
private String getName(Field f) {
CsvBindByName csvBindByName = f.getAnnotation(CsvBindByName.class);
CsvCustomBindByName csvCustomBindByName = f.getAnnotation(CsvCustomBindByName.class);
return csvCustomBindByName != null
? csvCustomBindByName.column() == null || csvCustomBindByName.column().isEmpty() ? f.getName() : csvCustomBindByName.column()
: csvBindByName.column() == null || csvBindByName.column().isEmpty() ? f.getName() : csvBindByName.column();
}
}
My POJO beans are annotated like this
public class Record {
#CsvBindByName(required = true)
#CsvPosition(position = 1)
Long id;
#CsvCustomBindByName(required = true, converter = BoolanCSVField.class)
#CsvPosition(position = 2)
Boolean deleted;
...
}
and final code for writer :
CustomMappingStrategy<Record> mappingStrategy = new CustomMappingStrategy<>(Record.class);
mappingStrategy.setType(Record.class);
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withApplyQuotesToAll(false)
.withOrderedResults(true)
.withMappingStrategy(mappingStrategy)
.build();
I hope it will helpful for someone
Here is the code to add support for #CsvBindByPosition based ordering to default HeaderColumnNameMappingStrategy. Tested for latest version 5.2
Approach is to store 2 map. First headerPositionMap to store the position element so same can used to setColumnOrderOnWrite , second columnMap from which we can lookup actual column name rather than capitalized one
public class HeaderColumnNameWithPositionMappingStrategy<T> extends HeaderColumnNameMappingStrategy<T> {
protected Map<String, String> columnMap;
#Override
public void setType(Class<? extends T> type) throws CsvBadConverterException {
super.setType(type);
columnMap = new HashMap<>(this.getFieldMap().values().size());
Map<String, Integer> headerPositionMap = new HashMap<>(this.getFieldMap().values().size());
for (Field field : type.getDeclaredFields()) {
if (field.isAnnotationPresent(CsvBindByPosition.class) && field.isAnnotationPresent(CsvBindByName.class)) {
int position = field.getAnnotation(CsvBindByPosition.class).position();
String colName = "".equals(field.getAnnotation(CsvBindByName.class).column()) ? field.getName() : field.getAnnotation(CsvBindByName.class).column();
headerPositionMap.put(colName.toUpperCase().trim(), position);
columnMap.put(colName.toUpperCase().trim(), colName);
}
}
super.setColumnOrderOnWrite((String o1, String o2) -> {
if (!headerPositionMap.containsKey(o1) || !headerPositionMap.containsKey(o2)) {
return 0;
}
return headerPositionMap.get(o1) - headerPositionMap.get(o2);
});
}
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
String[] headersRaw = super.generateHeader(bean);
return Arrays.stream(headersRaw).map(h -> columnMap.get(h)).toArray(String[]::new);
}
}
If you dont have getDeclaredAnnotationsByType method, but need the name of your original field name:
beanField.getField().getName()
public class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader() {
final int numColumns = findMaxFieldIndex();
if (!isAnnotationDriven() || numColumns == -1) {
return super.generateHeader();
}
header = new String[numColumns + 1];
BeanField beanField;
for (int i = 0; i <= numColumns; i++) {
beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField);
header[i] = columnHeaderName;
}
return header;
}
private String extractHeaderName(final BeanField beanField) {
if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotations().length == 0) {
return StringUtils.EMPTY;
}
return beanField.getField().getName();
}
}
Try something like below:
private static class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
String[] header;
public CustomMappingStrategy(String[] cols) {
header = cols;
}
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
return header;
}
}
Then use it as follows:
String[] columns = new String[]{"Name", "Age", "Company", "Salary"};
CustomMappingStrategy<Employee> mappingStrategy = new CustomMappingStrategy<Employee>(columns);
Where columns are columns of your bean and Employee is your bean
Great thread, I don't have any annotations in my pojo and this is how I did based on all the previous answers. Hope it helps others.
OpenCsv Version: 5.0
List readVendors = getFromMethod();
String[] fields= {"id","recordNumber","finVendorIdTb","finVenTechIdTb","finShortNameTb","finVenName1Tb","finVenName2Tb"};
String[] csvHeader= {"Id#","Shiv Record Number","Shiv Vendor Id","Shiva Tech Id#","finShortNameTb","finVenName1Tb","finVenName2Tb"};
CustomMappingStrategy<FinVendor> mappingStrategy = new CustomMappingStrategy(csvHeader);//csvHeader as per custom header irrespective of pojo field name
mappingStrategy.setType(FinVendor.class);
mappingStrategy.setColumnMapping(fields);//pojo mapping fields
StatefulBeanToCsv<FinVendor> beanToCsv = new StatefulBeanToCsvBuilder<FinVendor>(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withMappingStrategy(mappingStrategy).build();
beanToCsv.write(readVendors);
//custom mapping class as mentioned in the thread by many users
private static class CustomMappingStrategy extends ColumnPositionMappingStrategy {
String[] header;
public CustomMappingStrategy(String[] cols) {
header = cols;
}
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
super.generateHeader(bean);
return header;
}
}
Output:
Id# Shiv Record Number Shiv Vendor Id Fin Tech Id# finShortNameTb finVenName1Tb finVenName2Tb finVenDefaultLocTb
1 VEN00053 678 33316025986 THE ssOHIO S_2 THE UNIVERSITY CHK Test
2 VEN02277 1217 3044374205 Fe3 MECHA_1 FR3INC EFT-1
3 VEN03118 1310 30234484121 PE333PECTUS_1 PER332CTUS AR EFT-1 Test
The sebast26's first solution worked for me but for opencsv version 5.2 it requires a little change in the CustomMappingStrategy class:
class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
private static final String[] HEADER = new String[]{"TradeID", "GWML GUID", "MXML GUID", "GWML File", "MxML File", "MxML Counterparty", "GWML Counterparty"};
#Override
public String[] generateHeader() {
super.generateHeader(bean); // without this the file contains ONLY headers
return HEADER;
}
}
In case you need this to preserve column ordering from the original CSV: use a HeaderColumnNameMappingStrategy for reading, then use the same strategy for writing. "Same" in this case meaning not just the same class, but really the same object.
From the javadoc of StatefulBeanToCsvBuilder.withMappingStrategy:
It is perfectly legitimate to read a CSV source, take the mapping
strategy from the read operation, and pass it in to this method for a
write operation. This conserves some processing time, but, more
importantly, preserves header ordering.
This way you will get a CSV including headers, with columns in the same order as the original CSV.
Worked for me using OpenCSV 5.4.
It took me time also but I found the solution.
Add these annotations to your POJO: #CsvBindByName, #CsvBindByPosition with the right name and position of each object.
My POJO:
#JsonIgnoreProperties(ignoreUnknown = true)
#Getter
#Setter
public class CsvReport {
#CsvBindByName(column = "Campaign")
#CsvBindByPosition(position = 0)
private String program;
#CsvBindByName(column = "Report")
#CsvBindByPosition(position = 1)
private String report;
#CsvBindByName(column = "Metric Label")
#CsvBindByPosition(position = 2)
private String metric;
}
And add this code (my POJO called CsvReport):
ColumnPositionMappingStrategy<CsvReport> mappingStrategy = new ColumnPositionMappingStrategyBuilder<CsvReport>().build();
mappingStrategy.setType(CsvReport.class);
//add your headers in the sort you want to be in the file:
String[] columns = new String[] { "Campaign", "Report", "Metric Label"};
mappingStrategy.setColumnMapping(columns);
//Write your headers first in your chosen Writer:
Writer responseWriter = response.getWriter();
responseWriter.append(String.join(",", columns)).append("\n");
// Configure the CSV writer builder
StatefulBeanToCsv<CsvReport> writer = new StatefulBeanToCsvBuilder<CsvReport>(responseWriter)
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withOrderedResults(true) //I needed to keep the order, if you don't put false.
.withMappingStrategy(mappingStrategy)
.build();
String fileName = "your file name";
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,String.format("attachment; filename=%s", fileName));
writer.write(csvReports);
This will create a new CSV file with your printed headers and ordered fields.
I am using opencsv-4.0 to write a csv file and I need to add column headers in output file.
Here is my code.
public static void buildProductCsv(final List<Product> product,
final String filePath) {
try {
Writer writer = new FileWriter(filePath);
// mapping of columns with their positions
ColumnPositionMappingStrategy<Product> mappingStrategy = new ColumnPositionMappingStrategy<Product>();
// Set mappingStrategy type to Product Type
mappingStrategy.setType(Product.class);
// Fields in Product Bean
String[] columns = new String[] { "productCode", "MFD", "EXD" };
// Setting the colums for mappingStrategy
mappingStrategy.setColumnMapping(columns);
StatefulBeanToCsvBuilder<Product> builder = new StatefulBeanToCsvBuilder<Product>(writer);
StatefulBeanToCsv<Product> beanWriter = builder.withMappingStrategy(mappingStrategy).build();
// Writing data to csv file
beanWriter.write(product);
writer.close();
log.info("Your csv file has been generated!");
} catch (Exception ex) {
log.warning("Exception: " + ex.getMessage());
}
}
Above code create a csv file with data. But it not include column headers in that file.
How could I add column headers to output csv?
ColumnPositionMappingStrategy#generateHeader returns empty array
/**
* This method returns an empty array.
* The column position mapping strategy assumes that there is no header, and
* thus it also does not write one, accordingly.
* #return An empty array
*/
#Override
public String[] generateHeader() {
return new String[0];
}
If you remove MappingStrategy from BeanToCsv builder
// replace
StatefulBeanToCsv<Product> beanWriter = builder.withMappingStrategy(mappingStrategy).build();
// with
StatefulBeanToCsv<Product> beanWriter = builder.build();
It will write Product's class members as CSV header
If your Product class members names are
"productCode", "MFD", "EXD"
This should be the right solution
Else, add #CsvBindByName annotation
import com.opencsv.bean.CsvBindByName;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
public class CsvTest {
public static void main(String[] args) throws Exception {
Writer writer = new FileWriter(fileName);
StatefulBeanToCsvBuilder<Product> builder = new StatefulBeanToCsvBuilder<>(writer);
StatefulBeanToCsv<Product> beanWriter = builder.build();
List<Product> products = new ArrayList<>();
products.add(new Product("1", "11", "111"));
products.add(new Product("2", "22", "222"));
products.add(new Product("3", "33", "333"));
beanWriter.write(products);
writer.close();
}
public static class Product {
#CsvBindByName(column = "productCode")
String id;
#CsvBindByName(column = "MFD")
String member2;
#CsvBindByName(column = "EXD")
String member3;
Product(String id, String member2, String member3) {
this.id = id;
this.member2 = member2;
this.member3 = member3;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMember2() {
return member2;
}
public void setMember2(String member2) {
this.member2 = member2;
}
public String getMember3() {
return member3;
}
public void setMember3(String member3) {
this.member3 = member3;
}
}
}
Output:
"EXD","MFD","PRODUCTCODE"
"111","11","1"
"222","22","2"
"333","33","3"
Pay attention; class, getters & setters needs to be public due to the use of Reflection by OpenCSV library
You can append by annotation
public void export(List<YourObject> list, PrintWriter writer) throws Exception {
writer.append( buildHeader( YourObject.class ) );
StatefulBeanToCsvBuilder<YourObject> builder = new StatefulBeanToCsvBuilder<>( writer );
StatefulBeanToCsv<YourObject> beanWriter = builder.build();
beanWriter.write( mapper.map( list ) );
writer.close();
}
private String buildHeader(Class<YourObject> clazz) {
return Arrays.stream( clazz.getDeclaredFields() )
.filter( f -> f.getAnnotation( CsvBindByPosition.class ) != null
&& f.getAnnotation( CsvBindByName.class ) != null )
.sorted( Comparator.comparing( f -> f.getAnnotation( CsvBindByPosition.class ).position() ) )
.map( f -> f.getAnnotation( CsvBindByName.class ).column() )
.collect( Collectors.joining( "," ) ) + "\n";
}
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class YourObject {
#CsvBindByPosition(position = 0)
#CsvBindByName(column = "A")
private Long a;
#CsvBindByPosition(position = 1)
#CsvBindByName(column = "B")
private String b;
#CsvBindByPosition(position = 2)
#CsvBindByName(column = "C")
private String c;
}
I may have missed something obvious here but couldn't you just append your header String to the writer object?
Writer writer = new FileWriter(filePath);
writer.append("header1, header2, header3, ...etc \n");
// This will be followed by your code with BeanToCsvBuilder
// Note: the terminating \n might differ pending env.
Use a HeaderColumnNameMappingStrategy for reading, then use the same strategy for writing. "Same" in this case meaning not just the same class, but really the same object.
From the javadoc of StatefulBeanToCsvBuilder.withMappingStrategy:
It is perfectly legitimate to read a CSV source, take the mapping strategy from the read operation, and pass it in to this method for a write operation. This conserves some processing time, but, more importantly, preserves header ordering.
This way you will get a CSV including headers, with columns in the same order as the original CSV.
Worked for me using OpenCSV 5.4.
Use a custom strategy
static class CustomStrategy<T> extends ColumnPositionMappingStrategy<T> {
public String[] generateHeader() {
return this.getColumnMapping();
}
}
and on CSV object that you write do not forget to provide both
#CsvBindByName(column="UID")
#CsvBindByPosition(position = 3)
You could also override the generateHeaders method and return the column mapping that is set, which will have header row in csv
ColumnPositionMappingStrategy<Product> mappingStrategy = new ColumnPositionMappingStrategy<Product>() {
#Override
public String[] generateHeader(Product bean) throws CsvRequiredFieldEmptyException {
return this.getColumnMapping();
}
};
I have created a MappingsBean class where all the columns of the CSV file are specified. Next I parse XML files and create a list of mappingbeans. Then I write that data into CSV file as report.
I am using following annotations:
public class MappingsBean {
#CsvBindByName(column = "TradeID")
#CsvBindByPosition(position = 0)
private String tradeId;
#CsvBindByName(column = "GWML GUID", required = true)
#CsvBindByPosition(position = 1)
private String gwmlGUID;
#CsvBindByName(column = "MXML GUID", required = true)
#CsvBindByPosition(position = 2)
private String mxmlGUID;
#CsvBindByName(column = "GWML File")
#CsvBindByPosition(position = 3)
private String gwmlFile;
#CsvBindByName(column = "MxML File")
#CsvBindByPosition(position = 4)
private String mxmlFile;
#CsvBindByName(column = "MxML Counterparty")
#CsvBindByPosition(position = 5)
private String mxmlCounterParty;
#CsvBindByName(column = "GWML Counterparty")
#CsvBindByPosition(position = 6)
private String gwmlCounterParty;
}
And then I use StatefulBeanToCsv class to write into CSV file:
File reportFile = new File(reportOutputDir + "/" + REPORT_FILENAME);
Writer writer = new PrintWriter(reportFile);
StatefulBeanToCsv<MappingsBean> beanToCsv = new
StatefulBeanToCsvBuilder(writer).build();
beanToCsv.write(makeFinalMappingBeanList());
writer.close();
The problem with this approach is that if I use #CsvBindByPosition(position = 0) to control
position then I am not able to generate column names. If I use #CsvBindByName(column = "TradeID") then I am not able to set position of the columns.
Is there a way where I can use both annotations, so that I can create CSV files with column headers and also control column position?
Regards,
Vikram Pathania
I've had similar problem. AFAIK there is no build-in functionality in OpenCSV that will allow to write bean to CSV with custom column names and ordering.
There are two main MappingStrategyies that are available in OpenCSV out of the box:
HeaderColumnNameMappingStrategy: that allows to map CVS file columns to bean fields based on custom name; when writing bean to CSV this allows to change column header name but we have no control on column order
ColumnPositionMappingStrategy: that allows to map CSV file columns to bean fields based on column ordering; when writing bean to CSV we can control column order but we get an empty header (implementation returns new String[0] as a header)
The only way I found to achieve both custom column names and ordering is to write your custom MappingStrategy.
First solution: fast and easy but hardcoded
Create custom MappingStrategy:
class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
private static final String[] HEADER = new String[]{"TradeID", "GWML GUID", "MXML GUID", "GWML File", "MxML File", "MxML Counterparty", "GWML Counterparty"};
#Override
public String[] generateHeader() {
return HEADER;
}
}
And use it in StatefulBeanToCsvBuilder:
final CustomMappingStrategy<MappingsBean> mappingStrategy = new CustomMappingStrategy<>();
mappingStrategy.setType(MappingsBean.class);
final StatefulBeanToCsv<MappingsBean> beanToCsv = new StatefulBeanToCsvBuilder<MappingsBean>(writer)
.withMappingStrategy(mappingStrategy)
.build();
beanToCsv.write(makeFinalMappingBeanList());
writer.close()
In MappingsBean class we left CsvBindByPosition annotations - to control ordering (in this solution CsvBindByName annotations are not needed). Thanks to custom mapping strategy the header column names are included in resulting CSV file.
The downside of this solution is that when we change column ordering through CsvBindByPosition annotation we have to manually change also HEADER constant in our custom mapping strategy.
Second solution: more flexible
The first solution works, but it was not good for me. Based on build-in implementations of MappingStrategy I came up with yet another implementation:
class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader() {
final int numColumns = findMaxFieldIndex();
if (!isAnnotationDriven() || numColumns == -1) {
return super.generateHeader();
}
header = new String[numColumns + 1];
BeanField beanField;
for (int i = 0; i <= numColumns; i++) {
beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField);
header[i] = columnHeaderName;
}
return header;
}
private String extractHeaderName(final BeanField beanField) {
if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0) {
return StringUtils.EMPTY;
}
final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
}
You can use this custom strategy in StatefulBeanToCsvBuilder exactly this same as in the first solution (remember to invoke mappingStrategy.setType(MappingsBean.class);, otherwise this solution will not work).
Currently our MappingsBean has to contain both CsvBindByName and CsvBindByPosition annotations. The first to give header column name and the second to create ordering of columns in the output CSV header. Now if we change (using annotations) either column name or ordering in MappingsBean class - that change will be reflected in output CSV file.
Corrected above answer to match with newer version.
package csvpojo;
import org.apache.commons.lang3.StringUtils;
import com.opencsv.bean.BeanField;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvBindByName;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
super.setColumnMapping(new String[ FieldUtils.getAllFields(bean.getClass()).length]);
final int numColumns = findMaxFieldIndex();
if (!isAnnotationDriven() || numColumns == -1) {
return super.generateHeader(bean);
}
String[] header = new String[numColumns + 1];
BeanField<T> beanField;
for (int i = 0; i <= numColumns; i++) {
beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField);
header[i] = columnHeaderName;
}
return header;
}
private String extractHeaderName(final BeanField<T> beanField) {
if (beanField == null || beanField.getField() == null
|| beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0) {
return StringUtils.EMPTY;
}
final CsvBindByName bindByNameAnnotation = beanField.getField()
.getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
}
Then call this to generate CSV. I have used Visitors as my POJO to populate, update wherever necessary.
CustomMappingStrategy<Visitors> mappingStrategy = new CustomMappingStrategy<>();
mappingStrategy.setType(Visitors.class);
// writing sample
List<Visitors> beans2 = new ArrayList<Visitors>();
Visitors v = new Visitors();
v.set_1_firstName(" test1");
v.set_2_lastName("lastname1");
v.set_3_visitsToWebsite("876");
beans2.add(v);
v = new Visitors();
v.set_1_firstName(" firstsample2");
v.set_2_lastName("lastname2");
v.set_3_visitsToWebsite("777");
beans2.add(v);
Writer writer = new FileWriter("G://output.csv");
StatefulBeanToCsv<Visitors> beanToCsv = new StatefulBeanToCsvBuilder<Visitors>(writer)
.withMappingStrategy(mappingStrategy).withSeparator(',').withApplyQuotesToAll(false).build();
beanToCsv.write(beans2);
writer.close();
My bean annotations looks like this
#CsvBindByName (column = "First Name", required = true)
#CsvBindByPosition(position=1)
private String firstName;
#CsvBindByName (column = "Last Name", required = true)
#CsvBindByPosition(position=0)
private String lastName;
I wanted to achieve bi-directional import/export - to be able to import generated CSV back to POJO and visa versa.
I was not able to use #CsvBindByPosition for this, because in this case - ColumnPositionMappingStrategy was selected automatically. Per documents: this strategy requires that the file does NOT have a header.
What I've used to achieve the goal:
HeaderColumnNameMappingStrategy
mappingStrategy.setColumnOrderOnWrite(Comparator<String> writeOrder)
CsvUtils to read/write csv
import com.opencsv.CSVWriter;
import com.opencsv.bean.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.List;
public class CsvUtils {
private CsvUtils() {
}
public static <T> String convertToCsv(List<T> entitiesList, MappingStrategy<T> mappingStrategy) throws Exception {
try (Writer writer = new StringWriter()) {
StatefulBeanToCsv<T> beanToCsv = new StatefulBeanToCsvBuilder<T>(writer)
.withMappingStrategy(mappingStrategy)
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.build();
beanToCsv.write(entitiesList);
return writer.toString();
}
}
#SuppressWarnings("unchecked")
public static <T> List<T> convertFromCsv(MultipartFile file, Class clazz) throws IOException {
try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(reader).withType(clazz).build();
return csvToBean.parse();
}
}
}
POJO for import/export
public class LocalBusinessTrainingPairDTO {
//this is used for CSV columns ordering on exporting LocalBusinessTrainingPairs
public static final String[] FIELDS_ORDER = {"leftId", "leftName", "rightId", "rightName"};
#CsvBindByName(column = "leftId")
private int leftId;
#CsvBindByName(column = "leftName")
private String leftName;
#CsvBindByName(column = "rightId")
private int rightId;
#CsvBindByName(column = "rightName")
private String rightName;
// getters/setters omitted, do not forget to add them
}
Custom comparator for predefined String ordering:
public class OrderedComparatorIgnoringCase implements Comparator<String> {
private List<String> predefinedOrder;
public OrderedComparatorIgnoringCase(String[] predefinedOrder) {
this.predefinedOrder = new ArrayList<>();
for (String item : predefinedOrder) {
this.predefinedOrder.add(item.toLowerCase());
}
}
#Override
public int compare(String o1, String o2) {
return predefinedOrder.indexOf(o1.toLowerCase()) - predefinedOrder.indexOf(o2.toLowerCase());
}
}
Ordered writing for POJO (answer to initial question)
public static void main(String[] args) throws Exception {
List<LocalBusinessTrainingPairDTO> localBusinessTrainingPairsDTO = new ArrayList<>();
LocalBusinessTrainingPairDTO localBusinessTrainingPairDTO = new LocalBusinessTrainingPairDTO();
localBusinessTrainingPairDTO.setLeftId(1);
localBusinessTrainingPairDTO.setLeftName("leftName");
localBusinessTrainingPairDTO.setRightId(2);
localBusinessTrainingPairDTO.setRightName("rightName");
localBusinessTrainingPairsDTO.add(localBusinessTrainingPairDTO);
//Creating HeaderColumnNameMappingStrategy
HeaderColumnNameMappingStrategy<LocalBusinessTrainingPairDTO> mappingStrategy = new HeaderColumnNameMappingStrategy<>();
mappingStrategy.setType(LocalBusinessTrainingPairDTO.class);
//Setting predefined order using String comparator
mappingStrategy.setColumnOrderOnWrite(new OrderedComparatorIgnoringCase(LocalBusinessTrainingPairDTO.FIELDS_ORDER));
String csv = convertToCsv(localBusinessTrainingPairsDTO, mappingStrategy);
System.out.println(csv);
}
Read exported CSV back to POJO (addition to original answer)
Important: CSV can be unordered, as we are still using binding by name:
public static void main(String[] args) throws Exception {
//omitted code from writing
String csv = convertToCsv(localBusinessTrainingPairsDTO, mappingStrategy);
//Exported CSV should be compatible for further import
File temp = File.createTempFile("tempTrainingPairs", ".csv");
temp.deleteOnExit();
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
bw.write(csv);
bw.close();
MultipartFile multipartFile = new MockMultipartFile("tempTrainingPairs.csv", new FileInputStream(temp));
List<LocalBusinessTrainingPairDTO> localBusinessTrainingPairDTOList = convertFromCsv(multipartFile, LocalBusinessTrainingPairDTO.class);
}
To conclude:
We can read CSV to POJO, regardless of column order - because we are
using #CsvBindByName
We can control columns order on write using
custom comparator
In the latest version the solution of #Sebast26 does no longer work. However the basic is still very good. Here is a working solution with v5.0
import com.opencsv.bean.BeanField;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvBindByName;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
import org.apache.commons.lang3.StringUtils;
class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
final int numColumns = getFieldMap().values().size();
super.generateHeader(bean);
String[] header = new String[numColumns];
BeanField beanField;
for (int i = 0; i < numColumns; i++) {
beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField);
header[i] = columnHeaderName;
}
return header;
}
private String extractHeaderName(final BeanField beanField) {
if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(
CsvBindByName.class).length == 0) {
return StringUtils.EMPTY;
}
final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
}
And the model looks like this:
#CsvBindByName(column = "id")
#CsvBindByPosition(position = 0)
private Long id;
#CsvBindByName(column = "name")
#CsvBindByPosition(position = 1)
private String name;
And my generation helper looks something like this:
public static <T extends AbstractCsv> String createCsv(List<T> data, Class<T> beanClazz) {
CustomMappingStrategy<T> mappingStrategy = new CustomMappingStrategy<T>();
mappingStrategy.setType(beanClazz);
StringWriter writer = new StringWriter();
String csv = "";
try {
StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(writer)
.withSeparator(';')
.withMappingStrategy(mappingStrategy)
.build();
sbc.write(data);
csv = writer.toString();
} catch (CsvRequiredFieldEmptyException e) {
// TODO add some logging...
} catch (CsvDataTypeMismatchException e) {
// TODO add some logging...
} finally {
try {
writer.close();
} catch (IOException e) {
}
}
return csv;
}
The following works for me to map a POJO to a CSV file with custom column positioning and custom column headers (tested with opencsv-5.0) :
public class CustomBeanToCSVMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
String[] headersAsPerFieldName = getFieldMap().generateHeader(bean); // header name based on field name
String[] header = new String[headersAsPerFieldName.length];
for (int i = 0; i <= headersAsPerFieldName.length - 1; i++) {
BeanField beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField); // header name based on #CsvBindByName annotation
if (columnHeaderName.isEmpty()) // No #CsvBindByName is present
columnHeaderName = headersAsPerFieldName[i]; // defaults to header name based on field name
header[i] = columnHeaderName;
}
headerIndex.initializeHeaderIndex(header);
return header;
}
private String extractHeaderName(final BeanField beanField) {
if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0) {
return StringUtils.EMPTY;
}
final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
}
Pojo
Column Positioning in the generated CSV file:
The column positioing in the generated CSV file will be as per the annotation #CsvBindByPosition
Header name in the generated CSV file:
If the field has #CsvBindByName, the generated header will be as per the annonation
If the field doesn't have #CsvBindByName, then the generated header will be as per the field name
#Getter #Setter #ToString
public class Pojo {
#CsvBindByName(column="Voucher Series") // header: "Voucher Series"
#CsvBindByPosition(position=0)
private String voucherSeries;
#CsvBindByPosition(position=1) // header: "salePurchaseType"
private String salePurchaseType;
}
Using the above Custom Mapping Strategy:
CustomBeanToCSVMappingStrategy<Pojo> mappingStrategy = new CustomBeanToCSVMappingStrategy<>();
mappingStrategy.setType(Pojo.class);
StatefulBeanToCsv<Pojo> beanToCsv = new StatefulBeanToCsvBuilder<Pojo>(writer)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withMappingStrategy(mappingStrategy)
.build();
beanToCsv.write(pojoList);
thanks for this thread, it has been really useful for me... I've enhanced a little bit the provided solution in order to accept also POJO where some fields are not annotated (not meant to be read/written):
public class ColumnAndNameMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
super.setColumnMapping(new String[ getAnnotatedFields(bean)]);
final int numColumns = getAnnotatedFields(bean);
final int totalFieldNum = findMaxFieldIndex();
if (!isAnnotationDriven() || numColumns == -1) {
return super.generateHeader(bean);
}
String[] header = new String[numColumns];
BeanField<T> beanField;
for (int i = 0; i <= totalFieldNum; i++) {
beanField = findField(i);
if (isFieldAnnotated(beanField.getField())) {
String columnHeaderName = extractHeaderName(beanField);
header[i] = columnHeaderName;
}
}
return header;
}
private int getAnnotatedFields(T bean) {
return (int) Arrays.stream(FieldUtils.getAllFields(bean.getClass()))
.filter(this::isFieldAnnotated)
.count();
}
private boolean isFieldAnnotated(Field f) {
return f.isAnnotationPresent(CsvBindByName.class) || f.isAnnotationPresent(CsvCustomBindByName.class);
}
private String extractHeaderName(final BeanField beanField) {
if (beanField == null || beanField.getField() == null) {
return StringUtils.EMPTY;
}
Field field = beanField.getField();
if (field.getDeclaredAnnotationsByType(CsvBindByName.class).length != 0) {
final CsvBindByName bindByNameAnnotation = field.getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
if (field.getDeclaredAnnotationsByType(CsvCustomBindByName.class).length != 0) {
final CsvCustomBindByName bindByNameAnnotation = field.getDeclaredAnnotationsByType(CsvCustomBindByName.class)[0];
return bindByNameAnnotation.column();
}
return StringUtils.EMPTY;
}
}
If you're only interested in sorting the CSV columns based on the order in which member variables appear in your model class (CsvRow row in this example), then you can use a Comparator implementation to solve this in a rather simple manner. Here's an example that does this in Kotlin:
class ByMemberOrderCsvComparator : Comparator<String> {
private val memberOrder by lazy {
FieldUtils.getAllFields(CsvRow::class.java)
.map { it.getDeclaredAnnotation(CsvBindByName::class.java) }
.map { it?.column ?: "" }
.map { it.toUpperCase(Locale.US) } // OpenCSV UpperCases all headers, so we do this to match
}
override fun compare(field1: String?, field2: String?): Int {
return memberOrder.indexOf(field1) - memberOrder.indexOf(field2)
}
}
This Comparator does the following:
Fetches each member variable field in our data class (CsvRow)
Finds all the ones with the #CsvBindByName annotation (in the order you specified them in the CsvRow model)
Upper cases each to match the default OpenCsv implementation
Next, apply this Comparator to your MappingStrategy, so it'll sort based off the specified order:
val mappingStrategy = HeaderColumnNameMappingStrategy<OrderSummaryCsvRow>()
mappingStrategy.setColumnOrderOnWrite(ByMemberOrderCsvComparator())
mappingStrategy.type = CsvRow::class.java
mappingStrategy.setErrorLocale(Locale.US)
val csvWriter = StatefulBeanToCsvBuilder<OrderSummaryCsvRow>(writer)
.withMappingStrategy(mappingStrategy)
.build()
For reference, here's an example CsvRow class (you'll want to replace this with your own model for your needs):
data class CsvRow(
#CsvBindByName(column = "Column 1")
val column1: String,
#CsvBindByName(column = "Column 2")
val column2: String,
#CsvBindByName(column = "Column 3")
val column3: String,
// Other columns here ...
)
Which would produce a CSV as follows:
"COLUMN 1","COLUMN 2","COLUMN 3",...
"value 1a","value 2a","value 3a",...
"value 1b","value 2b","value 3b",...
The benefit of this approach is that it removes the need to hard-code any of your column names, which should greatly simplify things if you ever need to add/remove columns.
It is a solution for version greater than 4.3:
public class MappingBean {
#CsvBindByName(column = "column_a")
private String columnA;
#CsvBindByName(column = "column_b")
private String columnB;
#CsvBindByName(column = "column_c")
private String columnC;
// getters and setters
}
And use it as example:
import org.apache.commons.collections4.comparators.FixedOrderComparator;
...
var mappingStrategy = new HeaderColumnNameMappingStrategy<MappingBean>();
mappingStrategy.setType(MappingBean.class);
mappingStrategy.setColumnOrderOnWrite(new FixedOrderComparator<>("COLUMN_C", "COLUMN_B", "COLUMN_A"));
var sbc = new StatefulBeanToCsvBuilder<MappingBean>(writer)
.withMappingStrategy(mappingStrategy)
.build();
Result:
column_c | column_b | column_a
The following solution works with opencsv 5.0.
First, you need to inherit ColumnPositionMappingStrategy class and override generateHeader method to create your custom header for utilizing both CsvBindByName and CsvBindByPosition annotations as shown below.
import com.opencsv.bean.BeanField;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.bean.CsvBindByName;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
/**
* #param <T>
*/
class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
/*
* (non-Javadoc)
*
* #see com.opencsv.bean.ColumnPositionMappingStrategy#generateHeader(java.lang.
* Object)
*/
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
final int numColumns = getFieldMap().values().size();
if (numColumns == -1) {
return super.generateHeader(bean);
}
String[] header = new String[numColumns];
super.setColumnMapping(header);
BeanField<T, Integer> beanField;
for (int i = 0; i < numColumns; i++) {
beanField = findField(i);
String columnHeaderName = beanField.getField().getDeclaredAnnotation(CsvBindByName.class).column();
header[i] = columnHeaderName;
}
return header;
}
}
The next step is to use this mapping strategy while writing a bean to CSV as below.
CustomMappingStrategy<ScanReport> strategy = new CustomMappingStrategy<>();
strategy.setType(ScanReport.class);
// Write a bean to csv file.
StatefulBeanToCsv<ScanReport> beanToCsv = new StatefulBeanToCsvBuilder<ScanReport>(writer)
.withMappingStrategy(strategy).build();
beanToCsv.write(beanList);
I've improved on previous answers by removing all references to deprecated APIs while using the latest release of opencsv (4.6).
A Generic Kotlin Solution
/**
* Custom OpenCSV [ColumnPositionMappingStrategy] that allows for a header line to be generated from a target CSV
* bean model class using the following annotations when present:
* * [CsvBindByName]
* * [CsvCustomBindByName]
*/
class CustomMappingStrategy<T>(private val beanType: Class<T>) : ColumnPositionMappingStrategy<T>() {
init {
setType(beanType)
setColumnMapping(*getAnnotatedFields().map { it.extractHeaderName() }.toTypedArray())
}
override fun generateHeader(bean: T): Array<String> = columnMapping
private fun getAnnotatedFields() = beanType.declaredFields.filter { it.isAnnotatedByName() }.toList()
private fun Field.isAnnotatedByName() = isAnnotationPresent(CsvBindByName::class.java) || isAnnotationPresent(CsvCustomBindByName::class.java)
private fun Field.extractHeaderName() =
getAnnotation(CsvBindByName::class.java)?.column ?: getAnnotation(CsvCustomBindByName::class.java)?.column ?: EMPTY
}
Then use it as follows:
private fun csvBuilder(writer: Writer) =
StatefulBeanToCsvBuilder<MappingsBean>(writer)
.withSeparator(ICSVWriter.DEFAULT_SEPARATOR)
.withMappingStrategy(CustomMappingStrategy(MappingsBean::class.java))
.withApplyQuotesToAll(false)
.build()
// Kotlin try-with-resources construct
PrintWriter(File("$reportOutputDir/$REPORT_FILENAME")).use { writer ->
csvBuilder(writer).write(makeFinalMappingBeanList())
}
and for completeness, here's the CSV bean as a Kotlin data class:
data class MappingsBean(
#field:CsvBindByName(column = "TradeID")
#field:CsvBindByPosition(position = 0, required = true)
private val tradeId: String,
#field:CsvBindByName(column = "GWML GUID", required = true)
#field:CsvBindByPosition(position = 1)
private val gwmlGUID: String,
#field:CsvBindByName(column = "MXML GUID", required = true)
#field:CsvBindByPosition(position = 2)
private val mxmlGUID: String,
#field:CsvBindByName(column = "GWML File")
#field:CsvBindByPosition(position = 3)
private val gwmlFile: String? = null,
#field:CsvBindByName(column = "MxML File")
#field:CsvBindByPosition(position = 4)
private val mxmlFile: String? = null,
#field:CsvBindByName(column = "MxML Counterparty")
#field:CsvBindByPosition(position = 5)
private val mxmlCounterParty: String? = null,
#field:CsvBindByName(column = "GWML Counterparty")
#field:CsvBindByPosition(position = 6)
private val gwmlCounterParty: String? = null
)
I think the intended and most flexible way of handling the order of the header columns is to inject a comparator by HeaderColumnNameMappinStrategy.setColumnOrderOnWrite().
For me the most intuitive way was to write the CSV columns in the same order as they are specified in the CsvBean, but you can also adjust the Comparator to make use of your own annotations where you specify the order. Don´t forget to rename the Comparator class then ;)
Integration:
HeaderColumnNameMappingStrategy<MyCsvBean> mappingStrategy = new HeaderColumnNameMappingStrategy<>();
mappingStrategy.setType(MyCsvBean.class);
mappingStrategy.setColumnOrderOnWrite(new ClassFieldOrderComparator(MyCsvBean.class));
Comparator:
private class ClassFieldOrderComparator implements Comparator<String> {
List<String> fieldNamesInOrderWithinClass;
public ClassFieldOrderComparator(Class<?> clazz) {
fieldNamesInOrderWithinClass = Arrays.stream(clazz.getDeclaredFields())
.filter(field -> field.getAnnotation(CsvBindByName.class) != null)
// Handle order by your custom annotation here
//.sorted((field1, field2) -> {
// int field1Order = field1.getAnnotation(YourCustomOrderAnnotation.class).getOrder();
// int field2Order = field2.getAnnotation(YourCustomOrderAnnotation.class).getOrder();
// return Integer.compare(field1Order, field2Order);
//})
.map(field -> field.getName().toUpperCase())
.collect(Collectors.toList());
}
#Override
public int compare(String o1, String o2) {
int fieldIndexo1 = fieldNamesInOrderWithinClass.indexOf(o1);
int fieldIndexo2 = fieldNamesInOrderWithinClass.indexOf(o2);
return Integer.compare(fieldIndexo1, fieldIndexo2);
}
}
This can be done using a HeaderColumnNameMappingStrategy along with a custom Comparator as well.
Which is recommended by the official doc http://opencsv.sourceforge.net/#mapping_strategies
File reportFile = new File(reportOutputDir + "/" + REPORT_FILENAME);
Writer writer = new PrintWriter(reportFile);
final List<String> order = List.of("TradeID", "GWML GUID", "MXML GUID", "GWML File", "MxML File", "MxML Counterparty", "GWML Counterparty");
final FixedOrderComparator comparator = new FixedOrderComparator(order);
HeaderColumnNameMappingStrategy<MappingsBean> strategy = new HeaderColumnNameMappingStrategy<>();
strategy.setType(MappingsBean.class);
strategy.setColumnOrderOnWrite(comparator);
StatefulBeanToCsv<MappingsBean> beanToCsv = new
StatefulBeanToCsvBuilder(writer)
.withMappingStrategy(strategy)
.build();
beanToCsv.write(makeFinalMappingBeanList());
writer.close();
CustomMappingStrategy for generic class.
public class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
super.setColumnMapping(new String[ FieldUtils.getAllFields(bean.getClass()).length]);
final int numColumns = findMaxFieldIndex();
if (!isAnnotationDriven() || numColumns == -1) {
return super.generateHeader(bean);
}
String[] header = new String[numColumns + 1];
BeanField<T> beanField;
for (int i = 0; i <= numColumns; i++) {
beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField);
header[i] = columnHeaderName;
}
return header;
}
private String extractHeaderName(final BeanField<T> beanField) {
if (beanField == null || beanField.getField() == null
|| beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0) {
return StringUtils.EMPTY;
}
final CsvBindByName bindByNameAnnotation = beanField.getField()
.getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
}
POJO Class
public class Customer{
#CsvBindByPosition(position=1)
#CsvBindByName(column="CUSTOMER", required = true)
private String customer;
}
Client Class
List<T> data = getEmployeeRecord();
CustomMappingStrategy custom = new CustomMappingStrategy();
custom.setType(Employee.class);
StatefulBeanToCsv<T> writer = new StatefulBeanToCsvBuilder<T>(response.getWriter())
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withSeparator('|')
.withOrderedResults(false)
.withMappingStrategy(custom)
.build();
writer.write(reportData);
There is another version for 5.2 version because I have a problem with #CsvCustomBindByName annotation when I tried answers above.
I defined custom annotation :
#Target(ElementType.FIELD)
#Inherited
#Retention(RetentionPolicy.RUNTIME)
public #interface CsvPosition {
int position();
}
and custom mapping strategy
public class CustomMappingStrategy<T> extends HeaderColumnNameMappingStrategy<T> {
private final Field[] fields;
public CustomMappingStrategy(Class<T> clazz) {
fields = clazz.getDeclaredFields();
Arrays.sort(fields, (f1, f2) -> {
CsvPosition position1 = f1.getAnnotation(CsvPosition.class);
CsvPosition position2 = f2.getAnnotation(CsvPosition.class);
return Integer.compare(position1.position(), position2.position());
});
}
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
String[] header = new String[fields.length];
for (Field f : fields) {
CsvPosition position = f.getAnnotation(CsvPosition.class);
header[position.position() - 1] = getName(f);
}
headerIndex.initializeHeaderIndex(header);
return header;
}
private String getName(Field f) {
CsvBindByName csvBindByName = f.getAnnotation(CsvBindByName.class);
CsvCustomBindByName csvCustomBindByName = f.getAnnotation(CsvCustomBindByName.class);
return csvCustomBindByName != null
? csvCustomBindByName.column() == null || csvCustomBindByName.column().isEmpty() ? f.getName() : csvCustomBindByName.column()
: csvBindByName.column() == null || csvBindByName.column().isEmpty() ? f.getName() : csvBindByName.column();
}
}
My POJO beans are annotated like this
public class Record {
#CsvBindByName(required = true)
#CsvPosition(position = 1)
Long id;
#CsvCustomBindByName(required = true, converter = BoolanCSVField.class)
#CsvPosition(position = 2)
Boolean deleted;
...
}
and final code for writer :
CustomMappingStrategy<Record> mappingStrategy = new CustomMappingStrategy<>(Record.class);
mappingStrategy.setType(Record.class);
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withApplyQuotesToAll(false)
.withOrderedResults(true)
.withMappingStrategy(mappingStrategy)
.build();
I hope it will helpful for someone
Here is the code to add support for #CsvBindByPosition based ordering to default HeaderColumnNameMappingStrategy. Tested for latest version 5.2
Approach is to store 2 map. First headerPositionMap to store the position element so same can used to setColumnOrderOnWrite , second columnMap from which we can lookup actual column name rather than capitalized one
public class HeaderColumnNameWithPositionMappingStrategy<T> extends HeaderColumnNameMappingStrategy<T> {
protected Map<String, String> columnMap;
#Override
public void setType(Class<? extends T> type) throws CsvBadConverterException {
super.setType(type);
columnMap = new HashMap<>(this.getFieldMap().values().size());
Map<String, Integer> headerPositionMap = new HashMap<>(this.getFieldMap().values().size());
for (Field field : type.getDeclaredFields()) {
if (field.isAnnotationPresent(CsvBindByPosition.class) && field.isAnnotationPresent(CsvBindByName.class)) {
int position = field.getAnnotation(CsvBindByPosition.class).position();
String colName = "".equals(field.getAnnotation(CsvBindByName.class).column()) ? field.getName() : field.getAnnotation(CsvBindByName.class).column();
headerPositionMap.put(colName.toUpperCase().trim(), position);
columnMap.put(colName.toUpperCase().trim(), colName);
}
}
super.setColumnOrderOnWrite((String o1, String o2) -> {
if (!headerPositionMap.containsKey(o1) || !headerPositionMap.containsKey(o2)) {
return 0;
}
return headerPositionMap.get(o1) - headerPositionMap.get(o2);
});
}
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
String[] headersRaw = super.generateHeader(bean);
return Arrays.stream(headersRaw).map(h -> columnMap.get(h)).toArray(String[]::new);
}
}
If you dont have getDeclaredAnnotationsByType method, but need the name of your original field name:
beanField.getField().getName()
public class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] generateHeader() {
final int numColumns = findMaxFieldIndex();
if (!isAnnotationDriven() || numColumns == -1) {
return super.generateHeader();
}
header = new String[numColumns + 1];
BeanField beanField;
for (int i = 0; i <= numColumns; i++) {
beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField);
header[i] = columnHeaderName;
}
return header;
}
private String extractHeaderName(final BeanField beanField) {
if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotations().length == 0) {
return StringUtils.EMPTY;
}
return beanField.getField().getName();
}
}
Try something like below:
private static class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
String[] header;
public CustomMappingStrategy(String[] cols) {
header = cols;
}
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
return header;
}
}
Then use it as follows:
String[] columns = new String[]{"Name", "Age", "Company", "Salary"};
CustomMappingStrategy<Employee> mappingStrategy = new CustomMappingStrategy<Employee>(columns);
Where columns are columns of your bean and Employee is your bean
Great thread, I don't have any annotations in my pojo and this is how I did based on all the previous answers. Hope it helps others.
OpenCsv Version: 5.0
List readVendors = getFromMethod();
String[] fields= {"id","recordNumber","finVendorIdTb","finVenTechIdTb","finShortNameTb","finVenName1Tb","finVenName2Tb"};
String[] csvHeader= {"Id#","Shiv Record Number","Shiv Vendor Id","Shiva Tech Id#","finShortNameTb","finVenName1Tb","finVenName2Tb"};
CustomMappingStrategy<FinVendor> mappingStrategy = new CustomMappingStrategy(csvHeader);//csvHeader as per custom header irrespective of pojo field name
mappingStrategy.setType(FinVendor.class);
mappingStrategy.setColumnMapping(fields);//pojo mapping fields
StatefulBeanToCsv<FinVendor> beanToCsv = new StatefulBeanToCsvBuilder<FinVendor>(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withMappingStrategy(mappingStrategy).build();
beanToCsv.write(readVendors);
//custom mapping class as mentioned in the thread by many users
private static class CustomMappingStrategy extends ColumnPositionMappingStrategy {
String[] header;
public CustomMappingStrategy(String[] cols) {
header = cols;
}
#Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
super.generateHeader(bean);
return header;
}
}
Output:
Id# Shiv Record Number Shiv Vendor Id Fin Tech Id# finShortNameTb finVenName1Tb finVenName2Tb finVenDefaultLocTb
1 VEN00053 678 33316025986 THE ssOHIO S_2 THE UNIVERSITY CHK Test
2 VEN02277 1217 3044374205 Fe3 MECHA_1 FR3INC EFT-1
3 VEN03118 1310 30234484121 PE333PECTUS_1 PER332CTUS AR EFT-1 Test
The sebast26's first solution worked for me but for opencsv version 5.2 it requires a little change in the CustomMappingStrategy class:
class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
private static final String[] HEADER = new String[]{"TradeID", "GWML GUID", "MXML GUID", "GWML File", "MxML File", "MxML Counterparty", "GWML Counterparty"};
#Override
public String[] generateHeader() {
super.generateHeader(bean); // without this the file contains ONLY headers
return HEADER;
}
}
In case you need this to preserve column ordering from the original CSV: use a HeaderColumnNameMappingStrategy for reading, then use the same strategy for writing. "Same" in this case meaning not just the same class, but really the same object.
From the javadoc of StatefulBeanToCsvBuilder.withMappingStrategy:
It is perfectly legitimate to read a CSV source, take the mapping
strategy from the read operation, and pass it in to this method for a
write operation. This conserves some processing time, but, more
importantly, preserves header ordering.
This way you will get a CSV including headers, with columns in the same order as the original CSV.
Worked for me using OpenCSV 5.4.
It took me time also but I found the solution.
Add these annotations to your POJO: #CsvBindByName, #CsvBindByPosition with the right name and position of each object.
My POJO:
#JsonIgnoreProperties(ignoreUnknown = true)
#Getter
#Setter
public class CsvReport {
#CsvBindByName(column = "Campaign")
#CsvBindByPosition(position = 0)
private String program;
#CsvBindByName(column = "Report")
#CsvBindByPosition(position = 1)
private String report;
#CsvBindByName(column = "Metric Label")
#CsvBindByPosition(position = 2)
private String metric;
}
And add this code (my POJO called CsvReport):
ColumnPositionMappingStrategy<CsvReport> mappingStrategy = new ColumnPositionMappingStrategyBuilder<CsvReport>().build();
mappingStrategy.setType(CsvReport.class);
//add your headers in the sort you want to be in the file:
String[] columns = new String[] { "Campaign", "Report", "Metric Label"};
mappingStrategy.setColumnMapping(columns);
//Write your headers first in your chosen Writer:
Writer responseWriter = response.getWriter();
responseWriter.append(String.join(",", columns)).append("\n");
// Configure the CSV writer builder
StatefulBeanToCsv<CsvReport> writer = new StatefulBeanToCsvBuilder<CsvReport>(responseWriter)
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withOrderedResults(true) //I needed to keep the order, if you don't put false.
.withMappingStrategy(mappingStrategy)
.build();
String fileName = "your file name";
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,String.format("attachment; filename=%s", fileName));
writer.write(csvReports);
This will create a new CSV file with your printed headers and ordered fields.
Ok, so we all know that Maps are somewhat of a pain in JAXB.
I here present an alternative to the current solutions. My main objective is to get feedback on any and all potential problems with this solution. Maybe it is not even a good solution for some reasons.
When I played around with the standard Generic Map Adapter it seemed like the adapters for the classes were not used. The classes are instead scanned, forcing me to mark my data model with JAXB annotations and adding default constructors where I don't want them (I'm talking about complex classes that I want to store in Maps, not simple data types). Above all, this makes my internal data model public thereby breaking encapsulation since the generated XML is a direct representation of the internal structures.
The "workaround" I did was to combine the adapter with the Marshall.Listener and Unmarshall.Listner thereby being able to extract additional annotation information. A field would then be
#XmlElement(name = "testMap")
#XmlJavaTypeAdapter(MapAdapter.class)
#MapKeyValueAdapters(key=SomeComplexClassAdapter.class)
private final HashMap<SomeComplexClass, String> testMap2 = new HashMap<SomeComplexClass, String>();
This additional annotation accepts both key and value as arguments. If omitted the functionality falls back on standard qualification for the omitted. The example above will use the given adapter for the key and standard handling for the value.
Here the annotation.
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.xml.bind.annotation.adapters.XmlAdapter;
/**
* This annotation holds the adapters for the key and value used in the MapAdapter.
*/
#Retention(RUNTIME)
#Target({ FIELD })
public #interface MapKeyValueAdapters {
/**
* Points to the class that converts the value type to a bound type or vice versa. See {#link XmlAdapter} for more
* details.
*/
Class<? extends XmlAdapter<?, ?>> key() default UNDEFINED.class;
/**
* Points to the class that converts the value type to a bound type or vice versa. See {#link XmlAdapter} for more
* details.
*/
Class<? extends XmlAdapter<?, ?>> value() default UNDEFINED.class;
static final class UNDEFINED extends XmlAdapter<String, String> {
#Override
public String unmarshal(String v) throws Exception {
return null;
}
#Override
public String marshal(String v) throws Exception {
return null;
}
}
}
Here so the adapter
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.annotation.Annotation;
import java.lang.annotation.IncompleteAnnotationException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBIntrospector;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;
/**
* This class represents a general purpose Map adapter. It is capable of handling any type of class implementing the Map
* interface and has a no-args constructor.
*/
public class MapAdapter extends XmlAdapter<MapAdapter.Wrapper, Map<Object, Object>> {
private static final String XSI_NS = "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
private static final String XSI_TYPE = "xsi:type";
private static final String CDATA_START = "<![CDATA[";
private static final String CDATA_END = "]]>";
private final MarshallerListener marshallerListener = new MarshallerListener();
private final UnmarshallerListener unmarshallerListener = new UnmarshallerListener();
private final JAXBContext context;
public MapAdapter(JAXBContext inContext) {
context = inContext;
}
#SuppressWarnings({ "unchecked", "rawtypes" })
#Override
public Map<Object, Object> unmarshal(Wrapper inWrapper) throws Exception {
if (inWrapper == null) {
return null;
}
Info info = null;
for (Info element : unmarshallerListener.infoList) {
if (element.field.equals(inWrapper.field)) {
info = element;
}
}
if (info != null) {
Class<Map<Object, Object>> clazz = (Class<Map<Object, Object>>) Class.forName(inWrapper.mapClass);
Map<Object, Object> outMap = clazz.newInstance();
XmlAdapter<Object, Object> keyAdapter = null;
XmlAdapter<Object, Object> valueAdapter = null;
if (info.adapters.key() != MapKeyValueAdapters.UNDEFINED.class) {
keyAdapter = (XmlAdapter<Object, Object>) info.adapters.key().getConstructor().newInstance();
}
if (info.adapters.value() != MapKeyValueAdapters.UNDEFINED.class) {
valueAdapter = (XmlAdapter<Object, Object>) info.adapters.value().getConstructor().newInstance();
}
Unmarshaller um = context.createUnmarshaller();
for (MapEntry entry : inWrapper.mapList) {
Object key = ((JAXBElement) um.unmarshal(new StringReader(entry.key))).getValue();
if (keyAdapter != null) {
key = keyAdapter.unmarshal(key);
}
Object value = ((JAXBElement) um.unmarshal(new StringReader(entry.value))).getValue();
if (valueAdapter != null) {
value = valueAdapter.unmarshal(value);
}
outMap.put(key, value);
}
return outMap;
} else {
throw new IllegalStateException("Adapter info could not be found.");
}
}
#SuppressWarnings("unchecked")
#Override
public Wrapper marshal(Map<Object, Object> inMap) throws Exception {
if (inMap == null) {
return null;
}
Info info = null;
for (Info element : marshallerListener.infoList) {
if (element.map == inMap) {
info = element;
}
}
if (info != null) {
Wrapper outWrapper = new Wrapper();
outWrapper.mapClass = inMap.getClass().getName();
outWrapper.field = info.field;
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FRAGMENT, true);
JAXBIntrospector introspector = context.createJAXBIntrospector();
XmlAdapter<Object, Object> keyAdapter = null;
XmlAdapter<Object, Object> valueAdapter = null;
if (info.adapters.key() != MapKeyValueAdapters.UNDEFINED.class) {
keyAdapter = (XmlAdapter<Object, Object>) info.adapters.key().getConstructor().newInstance();
}
if (info.adapters.value() != MapKeyValueAdapters.UNDEFINED.class) {
valueAdapter = (XmlAdapter<Object, Object>) info.adapters.value().getConstructor().newInstance();
}
for (Map.Entry<?, ?> entry : inMap.entrySet()) {
MapEntry jaxbEntry = new MapEntry();
outWrapper.mapList.add(jaxbEntry);
Object key = entry.getKey();
if (key != null) {
Class<Object> clazz = Object.class;
if (keyAdapter != null) {
key = keyAdapter.marshal(key);
clazz = (Class<Object>) key.getClass();
}
if (introspector.getElementName(key) == null) {
// The value of clazz determines if the qualification is written or not; Object.class generates the
// qualification.
key = new JAXBElement<Object>(new QName("key"), clazz, key);
}
StringWriter writer = new StringWriter();
m.marshal(key, writer);
jaxbEntry.key = format("key", writer.toString());
}
Object value = entry.getValue();
if (value != null) {
Class<Object> clazz = Object.class;
if (valueAdapter != null) {
value = valueAdapter.marshal(value);
clazz = (Class<Object>) value.getClass();
}
if (introspector.getElementName(value) == null) {
// The value of clazz determines if the qualification is written or not; Object.class generates the
// qualification.
value = new JAXBElement<Object>(new QName("value"), clazz, value);
}
StringWriter writer = new StringWriter();
m.marshal(value, writer);
jaxbEntry.value = format("value", writer.toString());
}
}
return outWrapper;
} else {
throw new IllegalStateException("Adapter info could not be found.");
}
}
private String format(String inTagName, String inXML) {
String element = "<" + inTagName;
// Remove unneeded namespaces, they are already declared in the top node.
int beginIndex = inXML.indexOf(XSI_TYPE);
if (beginIndex != -1) {
int endIndex = inXML.indexOf(" ", beginIndex);
element += " " + inXML.substring(beginIndex, endIndex) + " " + XSI_NS;
}
beginIndex = inXML.indexOf('>');
element += inXML.substring(beginIndex);
return CDATA_START + element + CDATA_END;
}
#XmlType(name = "map")
static class Wrapper {
#XmlElement(name = "mapClass")
private String mapClass;
#XmlElement(name = "field")
private String field;
#XmlElementWrapper(name = "map")
#XmlElement(name = "entry")
private final List<MapEntry> mapList = new ArrayList<MapEntry>();
}
#XmlType(name = "mapEntry")
static class MapEntry {
#XmlElement(name = "key")
private String key;
#XmlElement(name = "value")
private String value;
}
public Marshaller.Listener getMarshallerListener() {
return marshallerListener;
}
public Unmarshaller.Listener getUnmarshallerListener() {
return unmarshallerListener;
}
private static class MarshallerListener extends Marshaller.Listener {
private final List<Info> infoList = new ArrayList<Info>();
#Override
public void beforeMarshal(Object inSource) {
extractInfo(infoList, inSource);
}
}
private class UnmarshallerListener extends Unmarshaller.Listener {
private final List<Info> infoList = new ArrayList<Info>();
#Override
public void beforeUnmarshal(Object inTarget, Object inParent) {
extractInfo(infoList, inTarget);
}
}
private static void extractInfo(List<Info> inList, Object inObject) {
for (Field field : inObject.getClass().getDeclaredFields()) {
for (Annotation a : field.getAnnotations()) {
if (a.annotationType() == XmlJavaTypeAdapter.class) {
if (((XmlJavaTypeAdapter) a).value() == MapAdapter.class) {
MapKeyValueAdapters adapters = field.getAnnotation(MapKeyValueAdapters.class);
if (adapters == null) {
throw new IncompleteAnnotationException(XmlJavaTypeAdapter.class, "; XmlJavaTypeAdapter specifies "
+ MapAdapter.class.getName() + " for field " + field.getName() + " in "
+ inObject.getClass().getName() + ". This must be used in combination with annotation "
+ MapKeyValueAdapters.class.getName());
}
try {
field.setAccessible(true);
Map<?, ?> value = (Map<?, ?>) field.get(inObject);
if (value != null) {
Info info = new Info();
info.field = field.getName();
info.map = value;
info.adapters = adapters;
inList.add(info);
}
} catch (Exception e) {
throw new RuntimeException("Failed extracting annotation information from " + field.getName() + " in "
+ inObject.getClass().getName(), e);
}
}
}
}
}
}
private static class Info {
private String field;
private Map<?, ?> map;
private MapKeyValueAdapters adapters;
}
}
Note that the adapter is capable of handling all types of Maps as long as it has a default constructor.
Finally the code to set up the usage of the adapter.
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
/**
* Singleton that manages the JAXB functionality.
*/
public enum JAXBManager {
INSTANCE;
private JAXBContext context;
private JAXBManager() {
try {
context = JAXBContext.newInstance(SomeComplexClass.class.getPackage().getName());
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
public Marshaller createMarshaller() throws JAXBException {
Marshaller m = context.createMarshaller();
MapAdapter adapter = new MapAdapter(context);
m.setAdapter(adapter);
m.setListener(adapter.getMarshallerListener());
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
return m;
}
public Unmarshaller createUnmarshaller() throws JAXBException {
Unmarshaller um = context.createUnmarshaller();
MapAdapter adapter = new MapAdapter(context);
um.setAdapter(adapter);
um.setListener(adapter.getUnmarshallerListener());
return um;
}
}
This could generate an output of something like
<testMap2>
<mapClass>java.util.HashMap</mapClass>
<field>testMap2</field>
<map>
<entry>
<key><![CDATA[<key><number>1357</number><type>Unspecified</type></key>]]></key>
<value><![CDATA[<value xsi:type="xs:string" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">gn</value>]]></value>
</entry>
</map>
</testMap2>
As can be seen the qualification info is not needed for the key since we already know the adapter to use.
Also note that I add CDATA to the output. I have implemented a simple character escape handler that respects this (not included in this code example).
Due to our release cycles I have a bit of time before the opportunity opens for implementing this functionality in our code so I therefore thought it would be wise to check with the community if there are any problems with this solution or if there are better ways already in the JAXB specification that I have overlooked. I also assume that there are sections of the code that can be done in better ways.
Thanks for comments.
Here is my proposal for a workaround:
Make the map XmlTransient
Use a wrapped List for the marshalling
reinit the map from the list whenever it is needed
if you need to keep the list and the map in sync use an add(order) function
Example Customer with a Map of Orders
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public static class Order {
#XmlID
String orderId;
String item;
int count;
}
#XmlRootElement(name = "customer")
#XmlAccessorType(XmlAccessType.FIELD)
public static class Customer {
String name;
String firstname;
#XmlElementWrapper(name = "orders")
#XmlElement(name = "order")
List<Order> orders = new ArrayList<Order>();
#XmlTransient
private Map<String, Order> ordermap = new LinkedHashMap<String, Order>();
/**
* reinitialize the order list
*/
public void reinit() {
for (Order order : orders) {
ordermap.put(order.orderId, order);
}
}
/**
* add the given order to the internal list and map
* #param order - the order to add
*/
public void addOrder(Order order) {
orders.add(order);
ordermap.put(order.orderId,order);
}
}
Example XML
<customer>
<name>Doe</name>
<firstname>John</firstname>
<orders>
<order>
<orderId>Id1</orderId>
<item>Item 1</item>
<count>1</count>
</order>
<order>
<orderId>Id2</orderId>
<item>Item 2</item>
<count>2</count>
</order>
</orders>
</customer>
Mininimal complete and verifiable example
An example according to
https://stackoverflow.com/help/mcve
can be found at
https://github.com/BITPlan/com.bitplan.simplerest/blob/master/src/test/java/com/bitplan/jaxb/TestJaxbFactory.java#L390