2016-09-27 30 views
0

我有一個附件類型列表[附件是一個類,其中包含一些getters和setter]。但由於某些原因,我需要將此列表轉換爲字符串,之後,我必須取從字符串列表。將字符串轉換爲我想要的對象

public class Attachment{ 

    private Integer attachmentCode; 

    private String attachmentDesc; 
} 

Attachment attach1 = new Attachment(); 
Attachment attach2 = new Attachment(); 

List<Attachment> tempList = new ArrayList<>(); 
tempList.add(attach1); 
tempList.add(attach2); 

HibernateClass record = new HibernateClass(); 
record.setValue(tempList .toString()); 

如果我想從這個String值中獲取Attachment對象,我該如何從這個列表中獲得我的值?

+2

你聽說過XML或JSON? – SimY4

+1

你說這個字符串在哪裏? –

+1

您尚未顯示任何希望_parse_的字符串示例。沒有一個樣本,我們真的幫不了你。 –

回答

0

我猜想有幾種方法。使用XML或JSON或任何其他文本格式也是一種有效的方法。

怎麼樣使用對象序列化和喜歡的Base64如下:

import java.io.*; 
import java.nio.charset.*; 
import java.util.*; 

public class Serialization { 

    public static void main(String[] args) throws Exception { 
     Attachment attach1 = new Attachment(); 
     Attachment attach2 = new Attachment(); 

     List<Attachment> tempList = new ArrayList<>(); 
     tempList.add(attach1); 
     tempList.add(attach2); 

     String value = serialize(tempList); 

     List<Attachment> attachments = deserialize(value); 
    } 

    private static List<Attachment> deserialize(String value) throws Exception { 
     byte[] decode = Base64.getDecoder().decode(value); 
     ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(decode)); 
     return (List<Attachment>) ois.readObject(); 
    } 

    private static String serialize(List<Attachment> tempList) throws IOException { 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     ObjectOutputStream os = new ObjectOutputStream(baos); 
     os.writeObject(tempList); 
     byte[] encode = Base64.getEncoder().encode(baos.toByteArray()); 
     return new String(encode, Charset.defaultCharset()); 
    } 

    private static class Attachment implements Serializable { 
     private Integer attachmentCode; 
     private String attachmentDesc; 
    } 

}