2016-09-27 3 views
0

첨부 파일 유형 목록 [첨부 파일은 일부 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 값에서 첨부 파일 객체를 가져 오려면 어떻게해야합니까?이 목록에서 값을 얻으려면 어떻게해야합니까?

+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; 
    } 

} 
관련 문제