XStream的Date转换 @XStreamConverter DateConverter

阅读更多
1.如果Date类型是元素,可参考http://huyumin.iteye.com/blog/2072675实现;

2.如果Date类型是属性,则要构造实现SingleValueConverter的转换类,方法如下:

public class XStreamDateConverter  implements SingleValueConverter {

	@Override
	public boolean canConvert(Class arg0) {
		return Date.class == arg0;
	}

	@Override
	public Object fromString(String arg0) {
		try {
			return DateUtil.parse(arg0, "yyyy-MM-dd");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String toString(Object arg0) {
		return DateUtil.getDateStrByPattern((Date) arg0, "yyyy-MM-dd");
	}

 }


在需要转换的Date属性上添加注解如下:
@XStreamConverter(value=XStreamDateConverter.class)
@XStreamAsAttribute
private Date startTime;
	
@XStreamConverter(value=XStreamDateConverter.class)
@XStreamAsAttribute
private Date endTime;


最后注册这个Converter就可以了
String xml = "";
XStream f = new XStream(new DomDriver()); 
f.registerConverter(new XStreamDateConverter());  
f.autodetectAnnotations(true);
f.fromXML(xml);
  • demo.rar (1.4 KB)
  • 下载次数: 1

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