2016-09-27 33 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; 
    } 

}