Home > Back-end >  Why am I getting ClassCastException when trying to deserialize a list
Why am I getting ClassCastException when trying to deserialize a list

Time:12-13

Person class

package model;

import java.io.Serializable;
import java.util.Objects;

public class Person implements Serializable {

    private String name;
    private String hobby;
    private Integer weight;
    private Integer age;

    public Person(String name, String hobby, Integer weight, Integer age) {
        this.name = name;
        this.hobby = hobby;
        this.weight = weight;
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getHobby() {
        return hobby;
    }
    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
    public Integer getWeight() {
        return weight;
    }
    public void setWeight(Integer weight) {
        this.weight = weight;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return
                "Name = '"   name   "'\n"  
                "Hobby = '"   hobby   "'\n"  
                "Weight = "   weight   "'\n"  
                "Age = "   age   "'\n";
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equals(name, person.name) && Objects.equals(hobby, person.hobby) && Objects.equals(weight, person.weight) && Objects.equals(age, person.age);
    }
    @Override
    public int hashCode() {
        return Objects.hash(name, hobby, weight, age);
    }
}

Serialization

public static void serialization(List<Person> fileList){
    if(fileList.size() > 0) {
        try (ObjectOutputStream writer = new ObjectOutputStream(new FileOutputStream("dat/serialPersons.ser"))) {
            for (int i = 0; i < fileList.size(); i  ) {
                if (fileList.get(i).getWeight() < 80) {
                    writer.writeObject(fileList.get(i));
                }
            }
            System.out.println("Serilization complete!");
        } catch (FileNotFoundException ex) {
            System.err.println(ex);
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }
    else{
        System.out.println("List is empty!!");
    }
}

Deserialization

public static void deserialization(){
    try(ObjectInputStream objectReader
                = new ObjectInputStream(new FileInputStream("dat/serialPersons.ser"))) {
        List<Person> deserializedList = (List<Person>)objectReader.readObject();

        deserializedList.forEach(System.out::println);
    } catch(IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

I am trying to learn some FILE handling in java and been stuck on this for 2 hours, I did multiple examples and the same exception comes out. When I try to deserialize the whole file as a list, I get a class cast exception

Exception in thread "main" java.lang.ClassCastException: class model.Person cannot be cast to class java.util.List (model.Person is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')
at main.Main.deserialization(Main.java:115)
at main.Main.main(Main.java:32)

If i use fileList.add(objectReader.readObject()); I only get the first one from the file and it is working but I only get the first one.

Any solution would be helpful.

EDIT: I used a whole list at once with conditioned objects and it all worked thanks

CodePudding user response:

I think you are writing "Person" object and reading list of "Person" objects. "writer.writeObject(fileList.get(i));" that code would write a single Person because fileList.get(index) returns a single form of Person, however on reading part you are expecting that object to be list of "Person".

For get rid of the issue tiny modification can save the flow, at least it might be worthy to try. But I'm not sure about your entire flow, it is just a suggestion. Hopefully help you :)

writer.writeObject(Arrays.asList(fileList.get(i)));

CodePudding user response:

The exception says you are trying to cast an instance of Person into a List(of Person). That's because readObject returns one Object(in this case one Person). To make a list of Person, split the file by appropriate delimiter(comma, tab, etc), and read one Object at a time. Or you have to define another class that can work like an array of Person(call it PersonList for example), and use readObject to make a PersonList instance. Or writing as ArrayList(or some other List implementations you like) and reading an ArrayList of Person can do the job.

CodePudding user response:

AS it : How do I write multiple objects to the serializable file and read them when the program is used again?

You try to cast a Person to List<Person>.

During Serialization, Write the array list directly.

Serialization

public static void serialization(List<Person> fileList){
    if(fileList.size() > 0) {
        // First create the list of persons to save
        List<Person> personsToSave = new ArrayList<Person>();

        try (ObjectOutputStream writer = new ObjectOutputStream(new FileOutputStream("dat/serialPersons.ser"))) {
            for (int i = 0; i < fileList.size(); i  ) {
                if (fileList.get(i).getWeight() < 80) {
                    personsToSave.add(fileList.get(i));
                }
            }
            // Then save
            writer.writeObject(personsToSave);
            System.out.println("Serilization complete!");
        } catch (FileNotFoundException ex) {
            System.err.println(ex);
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }
    else{
        System.out.println("List is empty!!");
    }
}
  • Related