如何将对象序列化为字符串 [英] How to serialize an object into a string

查看:53
本文介绍了如何将对象序列化为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够将一个对象序列化到一个文件中,然后再次恢复它,如下一个代码片段所示.我想将对象序列化为字符串并存储到数据库中.有人可以帮我吗?

LinkedList补丁 =//随便...FileOutputStream fileStream = new FileOutputStream("foo.ser");ObjectOutputStream os = new ObjectOutputStream(fileStream);os.writeObject(patches1);os.close();FileInputStream fileInputStream = new FileInputStream("foo.ser");ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream);对象一 = oInputStream.readObject();LinkedListpatch3 = (LinkedList) 一;os.close();

解决方案

Sergio:

您应该使用 BLOB.使用 JDBC 非常简单.

您发布的第二个代码的问题是编码.您应该另外对字节进行编码以确保它们都不会失败.

如果你仍然想把它写成一个字符串,你可以使用 java.util.Base64.

您仍然应该使用 CLOB 作为数据类型,因为您不知道序列化数据的长度.

这是如何使用它的示例.

import java.util.*;导入 java.io.*;/*** 使用示例序列化 SomeClass 实例*/公共类 ToStringSample {public static void main( String [] args ) 抛出 IOException,ClassNotFoundException {String string = toString( new SomeClass() );System.out.println("编码序列化版本");System.out.println(字符串);SomeClass some = ( SomeClass ) fromString( string );System.out.println( "

重构对象");System.out.println(一些);}/** 从 Base64 字符串中读取对象.*/私有静态对象 fromString( String s ) 抛出 IOException ,ClassNotFoundException {字节 [] 数据 = Base64.getDecoder().decode(s);ObjectInputStream ois = new ObjectInputStream(新的 ByteArrayInputStream( 数据 ) );对象 o = ois.readObject();ois.close();返回o;}/** 将对象写入 Base64 字符串.*/私有静态字符串 toString( Serializable o ) 抛出 IOException {ByteArrayOutputStream baos = new ByteArrayOutputStream();ObjectOutputStream oos = new ObjectOutputStream( baos );oos.writeObject( o );oos.close();返回 Base64.getEncoder().encodeToString(baos.toByteArray());}}/** 考试科目.一个非常简单的类.*/class SomeClass 实现 Serializable {私人最终静态长serialVersionUID = 1;//见下面尼克的评论int i = Integer.MAX_VALUE;字符串 s = "ABCDEFGHIJKLMNOP";Double d = new Double( -1.0 );公共字符串 toString(){返回SomeClass 实例说:别担心,"+ "我很健康.看,我的数据是 i = " + i+ ", s = " + s + ", d = " + d;}}

输出:

C:samples>javac *.javaC:samples>java ToStringSample编码序列化版本rO0ABXNyAAlTb21lQ2xhc3MAAAAAAAAAAQIAA0kAAWlMAAFkdAASTGphdmEvbGFuZy9Eb3VibGU7TAABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSilr+wQCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cL/wAAAAAAAAdAAQQUJDREVGR0hJSktMTU5PUA==重构对象SomeClass 实例说:别担心,我很健康.看,我的数据是 i = 2147483647,s = ABCDEFGHIJKLMNOP,d = -1.0

注意:对于 Java 7 及更早版本,您可以在此处查看原始答案>

I am able to serialize an object into a file and then restore it again as is shown in the next code snippet. I would like to serialize the object into a string and store into a database instead. Can anyone help me?

LinkedList<Diff_match_patch.Patch> patches = // whatever...
FileOutputStream fileStream = new FileOutputStream("foo.ser");
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(patches1);
os.close();

FileInputStream fileInputStream = new FileInputStream("foo.ser");
ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream);
Object one = oInputStream.readObject();
LinkedList<Diff_match_patch.Patch> patches3 = (LinkedList<Diff_match_patch.Patch>) one;
os.close();

解决方案

Sergio:

You should use BLOB. It is pretty straighforward with JDBC.

The problem with the second code you posted is the encoding. You should additionally encode the bytes to make sure none of them fails.

If you still want to write it down into a String you can encode the bytes using java.util.Base64.

Still you should use CLOB as data type because you don't know how long the serialized data is going to be.

Here is a sample of how to use it.

import java.util.*;
import java.io.*;

/** 
 * Usage sample serializing SomeClass instance 
 */
public class ToStringSample {

    public static void main( String [] args )  throws IOException,
                                                      ClassNotFoundException {
        String string = toString( new SomeClass() );
        System.out.println(" Encoded serialized version " );
        System.out.println( string );
        SomeClass some = ( SomeClass ) fromString( string );
        System.out.println( "

Reconstituted object");
        System.out.println( some );


    }

    /** Read the object from Base64 string. */
   private static Object fromString( String s ) throws IOException ,
                                                       ClassNotFoundException {
        byte [] data = Base64.getDecoder().decode( s );
        ObjectInputStream ois = new ObjectInputStream( 
                                        new ByteArrayInputStream(  data ) );
        Object o  = ois.readObject();
        ois.close();
        return o;
   }

    /** Write the object to a Base64 string. */
    private static String toString( Serializable o ) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream( baos );
        oos.writeObject( o );
        oos.close();
        return Base64.getEncoder().encodeToString(baos.toByteArray()); 
    }
}

/** Test subject. A very simple class. */ 
class SomeClass implements Serializable {

    private final static long serialVersionUID = 1; // See Nick's comment below

    int i    = Integer.MAX_VALUE;
    String s = "ABCDEFGHIJKLMNOP";
    Double d = new Double( -1.0 );
    public String toString(){
        return  "SomeClass instance says: Don't worry, " 
              + "I'm healthy. Look, my data is i = " + i  
              + ", s = " + s + ", d = " + d;
    }
}

Output:

C:samples>javac *.java

C:samples>java ToStringSample
Encoded serialized version
rO0ABXNyAAlTb21lQ2xhc3MAAAAAAAAAAQIAA0kAAWlMAAFkdAASTGphdmEvbGFuZy9Eb3VibGU7T
AABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSilr+w
QCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cL/wAAAAAAAAdAAQQUJ
DREVGR0hJSktMTU5PUA==


Reconstituted object
SomeClass instance says: Don't worry, I'm healthy. Look, my data is i = 2147483647, s = ABCDEFGHIJKLMNOP, d = -1.0

NOTE: for Java 7 and earlier you can see the original answer here

这篇关于如何将对象序列化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆