转换为可序列化的对象

问题描述:

这可能是一个愚蠢的问题,但我想将2维字符串数组转换为java中的可序列化对象。做这个的最好方式是什么?转换为可序列化的对象

+0

从下面发布的错误消息可以明显看出,您的问题与序列化无关。 -1。 – EJP 2011-06-02 09:01:34

+0

String,String []和String [] []都是可序列化的。 – 2011-06-02 09:28:09

数组已经可序列化。 String也是。你不需要更多。

下面是一个完整的例子:

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

/** 
* @author Colin Hebert 
*/ 
public class Serial { 

    public static void main(String[] args) 
      throws IOException, ClassNotFoundException { 
     PipedOutputStream pos = new PipedOutputStream(); 
     PipedInputStream pis = new PipedInputStream(pos); 

     String[][] strings = new String[][]{{"q","w","e"},{"a","s","d"},{"z", 
       "x","c"}}; 

     serialize(strings, pos); 

     String[][] strings2 = deserialize(pis); 

     System.out.println(Arrays.deepEquals(strings, strings2)); 
    } 

    public static String[][] deserialize(InputStream is) 
      throws IOException, ClassNotFoundException { 
     ObjectInputStream ois = new ObjectInputStream(is); 
     return (String[][]) ois.readObject(); 
    } 

    public static void serialize(String[][] array, OutputStream os) 
      throws IOException { 
     ObjectOutputStream oos = new ObjectOutputStream(os); 

     oos.writeObject(array); 
     oos.flush(); 
    } 
} 

资源:

+0

谢谢,我问这个问题的原因是因为即时通讯制作Web服务和入口点需要一个字符串[] []作为参数,但是当我使用Web服务进行测试时,我总是得到这个异常 – Davey 2011-06-02 08:48:35

+0

soapenv:Fault> soapenv:Server.userException org.xml.sax.SAXException:实测值的数组元素内的字符数据,而反序列化 faultstring> - 名称 ns1:主机名> soapenv:Fault> – Davey 2011-06-02 08:51:27

+0

@ user78087该错误与Serializable无关。 – EJP 2011-06-02 09:00:55

 ObjectOutputStream stream = null; 
    try { 
     stream = new ObjectOutputStream(out); 
     String strings[][] = { 
       {"a", "b", "c"}, 
       {"1", "2", "3"}, 
     }; 
     stream.writeObject(strings); 
    } catch (IOException e) { 
     e.printStackTrace(); //$REVIEW$ To change body of catch statement use File | Settings | File Templates. 
    } 

这里就是答案。数组默认情况下是可序列化的。只需将它像另一个可序列化对象一样写入ObjectOutputStream