JAXB 实现java对象与xml之间互相转换(二)


前面介绍的对象boy中只包含简单属性,如果boy中还包含其他对象该做如何处理呢?

@XmlRootElement(name="Root")
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Boy {
	
	private String name = "aa";
	private Address address;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	@XmlJavaTypeAdapter(AddressAdapter.class)
	public Address getAddress() {
		return address;
	}
	
	public void setAddress(Address address) {
		this.address = address;
	}
}
public class Address {

	private String address;
	
	public void setAddress(String address) {
		this.address = address;
	}

	public String getAddress() {
		return address;
	}

}
此时的boy对象中包含了Address对象,所以此时boy对象中的getAddress()须设置adapter,

创建AddressAdapter类,继承XmlAdapter

public class AddressAdapter extends XmlAdapter {

	@Override
	public Address unmarshal(String v) throws Exception {
		AddressImpl address = new AddressImpl();
		address.setAddress(v);
		return address;
	}

	@Override
	public String marshal(Address v) throws Exception {
		return v.getAddress();
	}

}

此时即可进行java对象转换为xml

public class JAXBTest {

	public static void main(String[] args) throws JAXBException {
		JAXBContext context = JAXBContext.newInstance(Boy.class);
		
		Marshaller marshaller = context.createMarshaller();
		
		System.out.println("----------marshaller--------------");
		Boy boy = new Boy();
		AddressImpl address = new AddressImpl();
		address.setAddress("BeiJing");
		boy.setAddress(address);
		marshaller.marshal(boy, System.out);
		
	}
	
}
最后打印结果为:

BeiJing
aa



你可能感兴趣的:(java,xml)