将String转换为我想要的对象

时间:2016-09-27 04:31:50

标签: java list string-parsing

我有一个附件类型列表[附件是一个包含一些getter和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对象,我该如何从此列表中获取我的值?

1 个答案:

答案 0 :(得分: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;
    }

}