Reading in from CSV numbers into strings with Jackson

Reading data from CSV, nothing simpler in Java with all those Jackson tutorials out there. Unless you want to read everything as string, that is. CsvMapper will take anything looking like a number and try to map it into some Integer or whatever, and if you needed strings in that field, well, too bad. Crash.

What worked earlier for me was a now deprecated feature of the mapper, namely:

CsvMapper.configure(Feature.WRITE_NUMBERS_AS_STRINGS, true);

Nowadays this format flag got moved into the JSON specific mapper, so it’s not format agnostic anymore and any future upgrade of the Jackson library might got me in trouble. Time to google (duckduckgo, actually) for solutions and lo, turned out I wasn’t doing it the “correct” way in the first place! One has to:

CsvMapper.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS)

which does exactly what it says – it doesn’t try anymore to be smart with the mapping and does only what’s programmed by schema to do. In my case, do nothing and leave everything as strings because I didn’t want or need any schema.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.