2016年7月7日星期四

Java_025:JAXB 批注 @XmlJavaTypeAdapter 使用例子

@XmlJavaTypeAdapter 适用于一些比较复杂的对象,这时需要包装一下这些对象,然后再使用。

1. DateAdapter.java

package jaxb;

import java.util.Date;
import java.text.SimpleDateFormat;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class DateAdapter extends XmlAdapter {

    private String pattern = "yyyy-MM-dd HH:mm:ss";
    SimpleDateFormat fmt = new SimpleDateFormat(pattern);

    @Override
    public Date unmarshal(String dateStr) throws Exception {
        return fmt.parse(dateStr);
    }

    @Override
    public String marshal(Date date) throws Exception {
        return fmt.format(date);
    }
}
 

2. Boy.java

package jaxb;

import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Boy {

    @XmlJavaTypeAdapter(DateAdapter.class)
    private Date date = new Date();
    private String name = "CY";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3. JAXBTest.java

package jaxb;

import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JAXBTest {

    public static void main(String[] args) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(Boy.class);

        Marshaller marshaller = context.createMarshaller();
        Unmarshaller unmarshaller = context.createUnmarshaller();

        Boy boy = new Boy();
        marshaller.marshal(boy, System.out);
        System.out.println();

//        String xml = "David";
//        Boy boy2 = (Boy) unmarshaller.unmarshal(new StringReader(xml));
//        System.out.println(boy2.name);
    }
}

4. 运行结果
生成的 XML 如下:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<boy>
  <name>CY</name>
  <date>2016-07-07 15:02:29</date>
</boy>

参考文献:
1. http://www.cnblogs.com/fragranting/archive/2012/03/25/xml--jaxb.html
2. http://alimama.iteye.com/blog/848895
3. http://www.cnblogs.com/holbrook/archive/2012/12/15/2818833.html