The errors you're getting appear to be related to bad imports
at your class file. Now even if that was OK, what you're trying to do you still not work.
Firstly, your CSV
file is missing a header (above country), secondly as with normal JSON
serialization/deserialization you need to perform this action against an object (a simple pojo). In your case your attempting to do this using object
which is wrong -- both syntactically as well as conceptually.
With the above on hand try the following. Modify your CSV
file to look like so:
country population mortality
spain 13000000 10000
france 30000000 15000
united kingdom 40000000 22000
belgium 20000000 50000
us 25000000 30000
The try the following code:
public class CsvParser {
public static void main(String... args) {
CsvSchema schema = CsvSchema
.emptySchema()
.withHeader();
ObjectReader reader = new CsvMapper()
.readerFor(MortalityEntry.class)
.with(schema);
List<MortalityEntry> results = null;
try {
MappingIterator<MortalityEntry> iterator = reader.readValues(Paths.get("/tmp/input.csv").toFile());
results = iterator.readAll();
} catch (IOException e) {
e.printStackTrace();
}
ObjectMapper objectMapper = new ObjectMapper();
try {
objectMapper.writeValue(Paths.get("/tmp/output.json").toFile(), results);
} catch (IOException e) {
e.printStackTrace();
}
}
private static class MortalityEntry {
private String country;
public String getCountry() { return country; }
public void setCountry(String country) { this.country = country; }
private Integer population;
public Integer getPopulation() { return population; }
public void setPopulation(Integer population) { this.population = population; }
private Integer mortality;
public Integer getMortality() { return mortality; }
public void setMortality(Integer mortality) { this.mortality = mortality; }
}
}
As you can see I'm using a simple pojo MortalityEntry
to deserialize (from CSV) and serialize (to JSON), letting Jackson do its magic.
This simple example should be enough to get you going.