JAXB
에 의해 채워지지 할 객체를 언 마샬링하려고
있지만, 가장 일반적인 솔루션 래퍼 클래스 (또는 더 나은, 일반적인, 재사용 가능한 래퍼 클래스)를 만드는 것입니다. 아래의 코드에는이 개념의 실제 예가 나와 있습니다. 코드가 자체 설명이되기를 바랍니다.
package com.quick;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD) // just to avoid the get and set methods
class Wrapper<T> {
@XmlAnyElement
List<T> list;
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD) // just to avoid the get and set methods
class Ship {
String id = "N" + System.nanoTime();
}
public class Main {
public static void main(String[] args) throws JAXBException {
// context, marshaller and unmarshaller
JAXBContext context = JAXBContext.newInstance(Ship.class, Wrapper.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Unmarshaller unmarshaller = context.createUnmarshaller();
// original list
List<Ship> originalList = new ArrayList<>();
originalList.add(new Ship());
originalList.add(new Ship());
originalList.add(new Ship());
// wrapper object
Wrapper<Ship> originalWraper = new Wrapper<>();
originalWraper.list = originalList;
// marshal the original wrapper and save the bytes in byteArray1
ByteArrayOutputStream os1 = new ByteArrayOutputStream();
marshaller.marshal(originalWraper, os1);
byte[] byteArray1 = os1.toByteArray();
// unmarshall the bytes
ByteArrayInputStream is = new ByteArrayInputStream(byteArray1);
Wrapper<Ship> unmarshaledWrapper = (Wrapper<Ship>) unmarshaller.unmarshal(is);
// THIS LIST SHOULD CONTAIN A COPY OF originalList
List<Ship> unmarshaledList = unmarshaledWrapper.list;
// marshal the unmarshaledWrapper (...) and sabe the bytes in byteArray2
ByteArrayOutputStream os2 = new ByteArrayOutputStream();
marshaller.marshal(unmarshaledWrapper, os2);
byte[] byteArray2 = os2.toByteArray();
// print the bytes, they should be the same
System.out.println(new String(byteArray1));
System.out.println(new String(byteArray2));
}
}
일반적인 아이디어는 필요에 따라 마샬링 또는 마샬링 할 수 있습니다 목록 (또는 배열)의 래퍼로서 작동 클래스를 만드는 것입니다.
Ship 클래스와 원래 입력 XML은 무엇입니까? 또한 ArrayList에 캐스팅하지 않아야합니다. 결국 CCE를 얻을 수 있습니다. – glee8e
xml은이 Ship이지만 Ship이 인터페이스라는 문제가있을 수 있습니까? 그리고 나는 ArrayList로 무언가를하려고 할 때 프로그램 끝에서 NullPointerExeption만을 얻습니다. –