QUESTION: Can you use CsvMapper/CsvSchema to convert csv to a map<string, object>
where the object is something other than string, like boolean or integer?
Details: I have some csv files that I want to convert directly to json. I don't have access to the POJO's. But I do have an xml schema file that contains the type information for the columns in the csv data.
After doing some searching I decided to use Jackson's CsvMapper/CsvSchema to convert the csv files to json. I created a CsvSchema with column type information then converted the csv files to a Map<> file then converted the map file to json. It all worked fine except for one thing. All the json properties were Strings, even the properties that the CsvSchema had defined as Boolean and Numeric types. Below is a small snippet that shows what I'm doing.
String csvEmployeeData="\"Bob\",25,true\n" +
"\"Joe\",35,false\n" +
"\"Tom\",45,false\n";
CsvSchema schema = CsvSchema.builder().addColumn("name", ColumnType.String)
.addColumn("age", ColumnType.NUMBER)
.addColumn("isManager", ColumnType.BOOLEAN)
.build();
CsvMapper csvMapper = new CsvMapper();
MappingIterator<Map<String, ? extends Object>> it = csvMapper.readerFor(Map.class)
.with(schema)
.readValues(csvEmployeeData);
List<Map<String, ? extends Object>> objectList=it.readAll();
Map<String, ? extends Object> employeeObj=objectList.get(0);
assertEquals("java.lang.Integer", employeeObj.get("age").getClass().getTypeName());
// Integer age=(Integer)employeeObj.get("age");
// java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
I'm reading the csv data in to a Map where the string is the property name and the Object is value. I thought the value type for Object would be based on the Schema ColumnType. I.e. if it was a ColumnType.BOOLEAN then Object would be Boolean. However all the Objects in the Map are String types.
I was assuming that the CsvSchema ColumnType's would be used in the conversion since in csv everything is a string so you don't need the schema for that. I'm clearly missing something. Surprisingly Google doesn't bring up a lot on using CsvMapper.
Does anyone know if possible to go from CSV to json and use the json types (bool/integer) or does everything have to be a string?