Home java Serialization of the collection in Java

Serialization of the collection in Java

Author

Date

Category

Is it possible to conduct serialization not class object, but a collection?

There is a code where I am trying to serve list , but the values ​​of the sheet are not saved to the file added to the project package, also does not pass deserialization, the READOBJECT method drops out an error?

Public Void Serialize (List & GT; String & LT; EXITDATA) {
 Try {
  FileoutPutTReam A = New FileOutputStream ("DataExit.json");
  ObjectOutputStream B = New ObjectOutputStream (A);
  B.WriteObject (EXITDATA);
  B.Flush ();
  B.Close ();
  a.close ();
 } Catch (IoException i) {
  I.PrintStackTrace ();
 }
}
Public void deserialize () {
 Try {
  FileoutPutTReam A = New FileOutputStream ("DataExit.json");
  ObjectOutputStream B = New ObjectOutputStream (A);
  ExitDeserial = (ArrayList) B.ReadObject (); // ?????
  B.Close ();
  a.close ();
 } Catch (IoException i) {
  I.PrintStackTrace ();
  Return;
 } Catch (CLASSNOTFOUNDEXCEPTION J) {
  System.out.PrintLN ("List Not Found");
  J.PrintStackTrace ();
  Return;
 }
 For (String T: ExitDeserial) {
  System.Out.printLN (T);
 }
}

Answer 1, Authority 100%

can be done like this:

string path = "d: \\ list.obj";
List & lt; Integer & gt; List;
If (! New File (Path) .exists ()) {
  List = list.of (1, 2, 3, 4, 5);
  Try (Final ObjectOutTReam ObjectoutStream = New ObjectoutStream (New FileoutPutStream (Path))) {
    ObjectOutputStream.WriteObject (LIST);
  }
} else {
  try (FileInputStream FileOutputStream = New FileInputStream (PATH);
     Final ObjectInputStream ObjectInputStream = New ObjectInputStream (FileOutputStream)) {
    List = (List) ObjectInputStream.ReadObject ();
  }
  System.out.PrintLN (List);
}

Conclusion:

[1, 2nd, 3, 4, 5]

You will not see the output immediately, as it will first record an object, and after the file exists, adds to the collection.

or generally make a separate class for this:

Public Final Class Serialize {
  Private Final String Path;
  Private Final File File;
  Private Object Object;
  Public Serialize (Final String Path) {
    this.path = path;
    this.File = New File (Path);
  }
  Public Void Serialize (Final Object Object) {
    try (final fileoutputstream fileoutputstream = new fileoutputstream (Path);
       Final ObjectoutStream ObjectOutputStream = New ObjectoutStream (FileoutPutStream)) {
      ObjectOutputStream.WriteObject (Object);
    } Catch (Final IoException IO) {
      //...Logo mistakes
    }
  }
  Public Object deserialize () {
    try (FileInputStream FileOutputStream = New FileInputStream (PATH);
       Final ObjectInputStream ObjectInputStream = New ObjectInputStream (FileOutputStream)) {
      Object = ObjectInputStream.ReadObject ();
    } Catch (Final IoException | ClassnotFoundException EX) {
      //...Logo mistakes
    }
    RETURN OBJECT;
  }
  Public Boolean IS () {
    Return null! = this.file & amp; & amp; this.file.exists ();
  }
}

and already use this:

Final Serialize Ser1 = New Serialize ("D: \\ List.Obj"),
        ser2 = new serialize ("D: \\ str.str");
if (! ser1.is ()) {
  Ser1.Serialize (List.of (1, 2, 3, 4, 5));
}
List & lt; Integer & gt; List = (List & lt; Integer & gt;) ser1.deserialize ();
System.out.PrintLN (List); // [1, 2, 3, 4, 5]
If (! ser2.is ()) {
  Ser2.Serialize ("String");
}
String String = (String) Ser2.Deserialize ();
System.Out.printLN (String); // String

MAO can immediately make a dynamic alignment to the desired type, during the call DEXERIALIZE .

public & lt; t & gt; T deserialize () { 
try (FileInputStream FileOutputStream = New FileInputStream (PATH);
    Final ObjectInputStream ObjectInputStream = New ObjectInputStream (FileOutputStream)) {
    Final Object Object = ObjectInputStream.ReadObject ();
    Final class & lt;? & gt; Class = object.getclass ();
    RETURN (T) Class.Cast (Object);
  } Catch (Final IoException | ClassnotFoundException EX) {
    //...Logo mistakes
    RETURN NULL;
  }
}

and you can already use this:

Final Serialize Ser1 = New Serialize ("D: \\ List.Obj"),
        ser2 = new serialize ("D: \\ str.str");
if (! ser1.is ()) {
  Ser1.Serialize (List.of (1, 2, 3, 4, 5));
}
List & lt; Integer & gt; List = ser1.deserialize ();
System.out.PrintLN (List); // [1, 2, 3, 4, 5]
If (! ser2.is ()) {
  Ser2.Serialize ("String");
}
String string = ser2.deserialize ();
System.Out.printLN (String); // String

Disconnecting similar with the option above.


Answer 2, Authority 67%

You must serialize the object. Yes, he may contain collections of other serializable objects.

All your objects should implement the Serializable interface, and contain the SerialVersionuid constant – the unique version of the serialized version version. So that the object could be deserialized, the current value in the class and in the serialized object must coincide.

Scheme Such:

Public Class Person Implements Serializable {
  Private Static Final Long SerialVersionuid = 1L;
  ...
  Private List & LT; Document & GT; Documents;
  Private TRANSIENT STRING SECRET; // this field will not serialized
}
Public Class Document IMPLEMENTS Serializable {
  Private Static Final Long SerialVersionuid = 1L;
  ...
}

You can see in detail here https://javarush.ru / GROUPS / POSTS / 2022-Serializacija-i-deserializacija-v-java


Answer 3

You can use wrapper for serialization / deserialization

import com.fasterxml.jackson.core.jsonProcessingException;
  Import com.fasterxml.jackson.core.type.typereference;
  Import com.fasterxml.jackson.databind.ObjectMapper;
  Import java.io.ioException;
  Import java.util.arraylist;
  Import java.util.list;
  Public Class Test {
    Public Static Void Main (String [] Args) Throws IoException {
      ArrayList & LT; SUSER & GT; Objects = New ArrayList & LT; Suser & GT; () {{
        Add (new SUXER ("S1", "S2"));
        Add (new SUXER ("S1", "S2"));
      }};
      Byte [] bytes = new ObjectMapper (). WriteValueAsbytes (Objects);
      ObjectMapper ObjectMapper = NEW OBJECTMAPPER ();
      List & lt; SUSER & GT; Susers = ObjectMapper.ReadValue (Bytes, New TypeReference & LT; List & LT; Suser & GT; & GT; () {
      });
      For (SUSER SUSER: SUSERS) {
        System.out.PrintLN (Suser.getfield1 () + "" + Suser.getfield2 ());
      }
    }
}
////////////////////////////////////
Import java.io.serializable;
Public Class SUSER IMPLEMENTS Serializable {
  Private String Field1;
  Private String Field2;
  Public Suser () {
  }
  Public Suser (String Field1, String Field2) {
    this.field1 = field1;
    this.field2 = field2;
  }
  Public String Getfield1 () {
    RETURN FIELD1;
  }
  Public String Getfield2 () {
    RETURN FIELD2;
  }
}
//////////////////////////////////// //
    & lt; dependency & gt;
      & lt; groupid & gt; com.fasterxml.jackson.core & lt; / groupid & gt;
      & lt; artifactid & gt; jackson-databind & lt; / artifactid & gt;
      & lt; version & gt; 2.12.1 & lt; / version & gt; // Check for New Version
    & lt; / dependency & gt;

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions