3

Consider I have a CSV as such:

name,city,active
abc,bcde,t
xyz,ghj,f

If I wanted to map this to a model how would I convert the 't' or 'f' to proper booleans. I am using jackson-dataformat-csv mapping to do this

CsvSchema csvSchema = CsvSchema.emptySchema().withHeader().withNullValue("");
CsvMapper csvMapper = new CsvMapper();
csvMapper.setPropertyNamingStrategy(SNAKE_CASE);
csvMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MappingIterator<Article> iterator = csvMapper.readerWithTypedSchemaFor(Object.class).with(csvSchema).readValues(fileFromResponse);
List<Object> data = iterator.readAll();

Currently the mapping fails with this error message:

Cannot deserialize value of type `java.lang.Boolean` from String "t": only "true" or "false" recognized

Is there any way I can specify in the schema that 't' or 'f' should be taken as booleans. Or is there another way I can deserialize it?

leoOrion
  • 1,833
  • 2
  • 26
  • 52
  • You can read them as strings and then write a simple util method to return you it's boolean result. – Oguz Ozcan Dec 29 '17 at 13:48
  • The csv is too long to read in memory. It leads to an out of memory error. That is why I'm trying to map it directly from file to model. – leoOrion Dec 29 '17 at 13:49
  • Take a look: https://stackoverflow.com/questions/34297506/how-can-i-serialiize-deserialize-a-boolean-value-from-fasterxml-jackson-as-an-in – PM 77-1 Dec 29 '17 at 13:53
  • that works for json. will it work with a csv file? – leoOrion Dec 29 '17 at 13:55
  • @PM77-1 json deserializer worked. If you want add it as an answer and I'll accept it. – leoOrion Dec 30 '17 at 05:29

1 Answers1

2

You could register a custom JacksonModule with a mapper for Boolean type:

private val YNToBooleanDeserializer = object : JsonDeserializer<Boolean>() {
    override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Boolean {
        return p.readValueAs(String::class.java) == "t"
    }
}

to register, use:

csvObjectMapper.registerModule(SimpleModule().addDeserializer(Boolean::class.java, YNToBooleanDeserializer))
Eddy
  • 74
  • 1
  • 9