import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@JsonPropertyOrder({"name", "age", "city"})
class Person {
private String name;
private int age;
private String city;
public Person(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", city='" + city + '\'' +
'}';
}
}
public class CsvProcessingExample {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
CsvMapper csvMapper = new CsvMapper();
CsvSchema schema = csvMapper.schemaFor(Person.class).withHeader();
ObjectMapper objectMapper = new ObjectMapper(csvMapper);
try {
objectMapper.writer(schema).writeValue(new File("persons.csv"), personList);
} catch (IOException e) {
e.printStackTrace();
}
try {
List<Person> deserializedPersonList = objectMapper.readerFor(Person.class).with(schema).readValue(new File("persons.csv"));
System.out.println(deserializedPersonList);
} catch (IOException e) {
e.printStackTrace();
}
}
}