0

I would like to save an array of objects that is custom as a file and re-read it back as an array of objects on program start in java. If I could also save it as JSON, it would be nice. I have tried some common methods but I get a error saying that my array is not serialiazable.

class ArrayOfObjects {

  public static void main (String[] args) throws Exception {

    Students[] studentArray = new Students[3];
    studentArray[0] = new Students();
    studentArray[0].age = 18;
    studentArray[0].name = "Jones";
    studentArray[1] = new Students();
    studentArray[1].age = 21;
    studentArray[1].name = "David";
    studentArray[2] = new Students();
    studentArray[2].age = 15;
    studentArray[2].name = "Jeremy";
  }  

}

class Students {

  int age;
  String name;

}

2 Answers 2

1

your class Students should implement Serialiazble

Sign up to request clarification or add additional context in comments.

2 Comments

That sort of worked. I got this now. pastebin.com/6fwMEptN Also, how do I re-read it into the same array?
you use ObjectInputStream
0
  1. If you want to save it in standard output, Students must implement Serializable.

  2. If you wan to save it as JSON, use Jackson (http://fasterxml.com/) and normalise it Java bean declaration to the class.

    class Students implemenst Serializable {
    
      private int age;
      private String name;
    
      public int getAge() {
          return age;
      }
    
      public void setAge(int age) {
          this.age = age;
      }
    
      public String getName() {
          return name;
      }
    
      public void setName(String name) {
          this.name = name;
      }
    
    }
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.