I never worked with JSON before and wanted to serialize an ArrayList<Person>
to a JSON file.
My writer class looks like this:
public class Writer {
public void write(){
ArrayList<Person> personList = new ArrayList<>();
Person p1 = new Person("James", "Bond", LocalDate.of(1997,9,22));
Person p2 = new Person("Santa", "Claus", LocalDate.of(1918,11,6));
Person p3 = new Person("Peter", "Griffin", LocalDate.of(1978,3,24));
Person p4 = new Person("Lois", "Griffin", LocalDate.of(1982,7,14));
personList.add(p1);
personList.add(p2);
personList.add(p3);
personList.add(p4);
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
try {
writer.writeValue(new File(System.getProperty("user.dir")+"/File/Person.json"), personList);
} catch (IOException e) {
e.printStackTrace();
}
}
And my reader class looks like this:
public class Reader {
public void read(){
ObjectMapper mapper = new ObjectMapper();
try {
ArrayList<Person> liste = mapper.readValue(new FileInputStream("File/Personen.json"), ArrayList.class);
System.out.println("Read: " + liste.get(0));
} catch (IOException e) {
e.printStackTrace();
}
}
The first Object in the list looks like this:
Gelesen: {firstname=James, lastname=Bond, birthday={year=1997, month=SEPTEMBER, monthValue=9, dayOfMonth=22, chronology={id=ISO, calendarType=iso8601}, era=CE, dayOfYear=265, dayOfWeek=MONDAY, leapYear=false}}
How do I convert this JSON String back to a java object of the class "person"? Is anything wrong with my serialization/deserialization ?
EDIT: I wanted to check wether my person in the list that is deserialized from the JSON file is the same as the original person so I wrote System.out.println(list.get(0).getFirstname()
and then I got an java.lang.ClassCastException: java.base/java.util.LinkedHashMap cannot be cast to Person