I need to map a CSV column name to a POJO class in JAVA. But the names in the CSV files and Java classes are a little different. Also, I don't need all columns in the CSV files to be mapped to POJOs, I only need certain columns. Tried mapping using column name.
But the below implementation only works only if the CSV column names and POJO class field names match.
I am using Super CSV for my implementation. Any annotations/ways to handle this [different names in POJO fields / CSV columns], I am really stuck here.
Code:
ICsvBeanReader beanReader = null;
Employee employee;
//columns to be mapped
final List<String> columnsToMap = Arrays.asList("emp_id_no", "emp_name", "emp_dept");
HashMap<String, Object> employeeMap;
try {
beanReader = new CsvBeanReader(new InputStreamReader(inputStream, "UTF-8"),
new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE).build());
// read the CSV header (and set any unwanted columns to null)
String[] header = beanReader.getHeader(true);
for (int i = 0; i < header.length; i++) {
if (!columnsToMap.contains(header[i])) {
header[i] = null;
}
}
for (String s: header) {
System.out.println(s);
}
employeeMap = new HashMap<String, Object>();
while ((employee = beanReader.read(Employee.class, header)) != null) {
System.out.println(employee);
}
}
csv:
emp_id,emp_name,emp_phone_no,emp_dept,emp_address_details
1,"abc","finance",123,"hgdhgede"
2,"def","hr",456,"dwnhffjefnv"
POJO will be:
public class Employee {
@Getter
@Setter
private int empId;
@Getter
@Setter
private String empName;
@Getter
@Setter
private String empDept;
}