Java 中将对象序列化为字符串
本教程演示如何在 Java 中将对象序列化为字符串。
Java 中将对象序列化为字符串
要将对象序列化为字符串,我们可以使用 base 64 编码。我们可以通过创建两个类来实现序列化,一个类将实现 Serializable
类,另一个类将用于创建 Serializable
类的对象并对其进行序列化。
请参阅 Java 示例:
package delftstack;
import java.util.*;
import java.io.*;
public class Serialize_Object {
public static void main( String [] args ) throws IOException,
ClassNotFoundException {
String Serialized_String = To_String( new Demo_Serialize() );
System.out.println(" The Serialized String " );
System.out.println( Serialized_String );
Demo_Serialize Original_object = ( Demo_Serialize ) From_String( Serialized_String );
System.out.println( "\n\nThe Original String");
System.out.println( Original_object );
}
private static Object From_String( String s ) throws IOException ,
ClassNotFoundException {
byte [] Byte_Data = Base64.getDecoder().decode( s );
ObjectInputStream Object_Input_Stream = new ObjectInputStream( new ByteArrayInputStream(Byte_Data) );
Object Demo_Object = Object_Input_Stream.readObject();
Object_Input_Stream.close();
return Demo_Object;
}
private static String To_String( Serializable Demo_Object ) throws IOException {
ByteArrayOutputStream Byte_Array_Output_Stream = new ByteArrayOutputStream();
ObjectOutputStream Object_Output_Stream = new ObjectOutputStream( Byte_Array_Output_Stream );
Object_Output_Stream.writeObject( Demo_Object );
Object_Output_Stream.close();
return Base64.getEncoder().encodeToString(Byte_Array_Output_Stream.toByteArray());
}
}
class Demo_Serialize implements Serializable {
private final static long serialVersionUID = 1;
int i = Integer.MAX_VALUE;
String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Double d = new Double( -1.0 );
public String toString(){
return "DelftStack is a resource for everyone interested in "
+ "programming, embedded software, and electronics. "
+ "It covers the programming languages like Python, "
+ "C/C++, C#, and so on in this website's first "
+ "development stage. Open-source hardware also falls "
+ "in the website's scope, like Arduino, Raspberry Pi, and BeagleBone.";
}
}
上面的代码将创建一个 Demo_Serialize
类的对象并将该对象序列化为一个字符串。上面代码的输出将是:
The Serialized String
rO0ABXNyABlkZWxmdHN0YWNrLkRlbW9fU2VyaWFsaXplAAAAAAAAAAECAANJAAFpTAABZHQAEkxqYXZhL2xhbmcvRG91YmxlO0wAAXN0ABJMamF2YS9sYW5nL1N0cmluZzt4cH////9zcgAQamF2YS5sYW5nLkRvdWJsZYCzwkopa/sEAgABRAAFdmFsdWV4cgAQamF2YS5sYW5nLk51bWJlcoaslR0LlOCLAgAAeHC/8AAAAAAAAHQAGkFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFla
The Original String
DelftStack is a resource for everyone interested in programming, embedded software, and electronics. It covers the programming languages like Python, C/C++, C#, and so on in this website's first development stage. Open-source hardware also falls in the website's scope, like Arduino, Raspberry Pi, and BeagleBone.
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。