Android learning essay – three ways of serialization

Time:2022-1-11

serialize

1.Serializable

​ Java serialization refers to the process of converting Java objects into byte sequences

Java deserialization refers to the process of restoring byte sequences to Java objects.

There are three implementations of serialization and deserialization:

① If student class only implements serializable interface, it can be serialized and deserialized as follows.

Objectoutputstream uses the default serialization method to serialize non transient instance variables of student objects. 
         Objcetinputstream uses the default deserialization method to deserialize the non transient instance variables of the student object.

② If the student class only implements the serializable interface and defines readObject (objectinputstream in) and writeobject (objectoutputstream out), the following methods are used for serialization and deserialization.

Objectoutputstream calls the writeobject (objectoutputstream out) method of the student object for serialization. 
       Objectinputstream will call the readObject (objectinputstream in) method of the student object for deserialization.

③ If the student class implements the externalizable interface, and the student class must implement the readexternal (objectinput in) and writeexternal (objectoutput out) methods, serialize and deserialize as follows.

Objectoutputstream calls the writeexternal (objectoutput out) method of the student object for serialization. 
       Objectinputstream will call the readexternal (objectinput in) method of the student object for deserialization.
//Serialize instance
public class SerializableTest {
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            //Serialization
            FileOutputStream fos = new FileOutputStream("object.out");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            Student student1 = new Student("lihao", "wjwlh", "21");
            oos.writeObject(student1);
            oos.flush();
            oos.close();
            //Deserialization
            FileInputStream fis = new FileInputStream("object.out");
            ObjectInputStream ois = new ObjectInputStream(fis);
            Student student2 = (Student) ois.readObject();
            System.out.println(student2.getUserName()+ " " +
                    student2.getPassword() + " " + student2.getYear());
    }
 
}
//Object
public class Student implements Serializable{                             
                                                                          
    private static final long serialVersionUID = -6060343040263809614L;   
                                                                          
    private String userName;                                              
    private String password;                                              
    private String year;                                                  
                                                                          
    public String getUserName() {                                         
        return userName;                                                  
    }                                                                     
                                                                          
    public String getPassword() {                                         
        return password;                                                  
    }                                                                     
                                                                          
    public void setUserName(String userName) {                            
        this.userName = userName;                                         
    }                                                                     
                                                                          
    public void setPassword(String password) {                            
        this.password = password;                                         
    }                                                                     
                                                                          
    public String getYear() {                                             
        return year;                                                      
    }                                                                     
                                                                          
    public void setYear(String year) {                                    
        this.year = year;                                                 
    }                                                                     
                                                                          
    public Student(String userName, String password, String year) {       
        this.userName = userName;                                         
        this.password = password;                                         
        this.year = year;                                                 
    }                                                                     
}

2.Parcelable

public class NewClient implements Parcelable {

    public int id;
    public String name;
    public User user;

    /**
     *The content description of the current object. Generally, 0 is returned
     * @return
     */
    @Override
    public int describeContents() {
        return 0;
    }

    /**
     *Writes the current object to the serialization structure
     * @param dest
     * @param flags
     */
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.id);
        dest.writeString(this.name);
        dest.writeParcelable(this.user,0);
    }

    public NewClient() {
    }

    /**
     *Creates the original object from the serialized object
     * @param in
     */
    protected NewClient(Parcel in) {
        this.id = in.readInt();
        this.name = in.readString();
       //User is another serialized object. This method sequence needs to pass the context class loader of the current thread, otherwise it will report an error that the class cannot be found
       this.user=in.readParcelable(Thread.currentThread().getContextClassLoader());
    }

    /**
     *Public static final cannot be missing, and the name of the internal object creator cannot be changed. It must be capitalized.
     *Override two methods in the interface:
     *Createfromparcel (parcel in) reads the transfer data value from the parcel container, encapsulates it into a Parcelable object, and returns it to the logic layer,
     *Newarray (int size) creates an array of type T and length size for external class deserialization.
     */
    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        /**
         *Creates the original object from the serialized object
         */
        @Override
        public NewClient createFromParcel(Parcel source) {
            return new NewClient(source);
        }

        /**
         *Creates an array of original objects of the specified length
         * @param size
         * @return
         */
        @Override
        public NewClient[] newArray(int size) {
            return new NewClient[size];
        }
    };
}

3.XML JSON

//Serialization
Gson gson=new Gson();
gson. Tojson (object);
//Deserialization
Type type=new TypeToken>(){}.getType();
gson. From JSON (JSON data of the object, type);

Recommended Today

Flutter state management based on riverpod

original text https://itnext.io/flutter-sta… code https://github.com/iisprey/ri… reference resources https://itnext.io/a-minimalis… https://pub.dev/packages/stat… https://iisprey.medium.com/ge… https://iisprey.medium.com/ho… text As I promised last week, I will show you my own path to a final state management solution Riverpod + StateNotifier + Hooks + Freezed Riverpod is great! But there are not many good examples. Only the most basic, that’s all. This time, […]