JAXB学习笔记(二)
上个例子中人说Date类型序列化出的字符串不好看啊,那我们来处理一下;
需要使用注释 @XmlJavaTypeAdapter ,并且创造一个转换类
Java代码
package cn.uyunsky.blog.xml.demo2;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Date;
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.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>看个类型转换</p>
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Persion {
private Integer userid;
private String username;
@XmlJavaTypeAdapter(value = DateXmlAdapter.class)
private Date birthday;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Persion [userid=");
builder.append(userid);
builder.append(", username=");
builder.append(username);
builder.append(", birthday=");
builder.append(birthday);
builder.append("]");
return builder.toString();
}
public static void main(String[] args) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Persion.class);
Persion persion = new Persion();
persion.setUserid(112);
persion.setUsername("就不告诉你");
persion.setBirthday(new Date());
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(persion, writer);
String xml = writer.getBuffer().toString();
System.out.println(xml);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Object bean = unmarshaller.unmarshal(new StringReader(xml));
System.out.println(bean);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
转换类
Java代码
package cn.uyunsky.blog.xml.demo2;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
/**
* <p>日期转换类,注意看XmlAdapter源码,使用泛型很方便,否则代码中需要Object的强制类型转换</p>
* <pre>
public abstract class XmlAdapter<ValueType, BoundType>
{
public abstract BoundType unmarshal(ValueType paramValueType)
throws Exception;
public abstract ValueType marshal(BoundType paramBoundType)
throws Exception;
}
* <pre>
*/
public class DateXmlAdapter extends XmlAdapter<String, Date> {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
/**
* 将xml中的值转换为bean中的对象
*/
@Override
public Date unmarshal(String paramValueType) throws Exception {
return format.parse(paramValueType);
}
/**
* 将bean中的对象转换为xml字符串
*/
@Override
public String marshal(Date paramBoundType) throws Exception {
&nbs
补充:软件开发 , Java ,