XStream自定义时间转换器(简单)

      XStream自定义转换器很简单,主要用于满足一些个性化的需要,如从xml文件给JavaBean赋值时候时间字段值为"",这时候默认的转换器报错了,需要自定义一个转换器。

 

     参考了博文:

     http://www.jiucool.com/blog/xstream-custom-type-converter-converter/

    

     XML文件如下:

    

<Fault>
  <faultId>1</faultId>
  <deviceId>10023</deviceId>
  <deviceModel>10023</deviceModel>
  <processStat>1</processStat>
  <faultDesc>电视机坏</faultDesc>
  <process>进行更换</process>
  <timeoutReason>超时原因</timeoutReason>
  <timeout>1.25</timeout>
  <protime>1.24</protime>
  <faulttime></faulttime>
  <closetime>2014-03-04 </closetime>
</Fault>

 

    faulttime是java.util.Date类型,如果没有值就返回NULL,转换器如下:

   

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

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;


public class MyDateConverter implements Converter {
	private String dateformatter= "yyyy-MM-dd HH:mm:ss";

	/**
	 * 默认转换格式
	 * 
	 * @author jiucool.com
	 */
	public MyDateConverter() {
		super();
		this.dateformatter = "yyyy-MM-dd HH:mm:ss";
	}

	public MyDateConverter(String dateformatter) {
		super();
		this.dateformatter = dateformatter;
	}

	@Override
	public boolean canConvert(Class clazz) {
		return Date.class.isAssignableFrom(clazz);
	}

	@Override
	public void marshal(Object value, HierarchicalStreamWriter writer,
			MarshallingContext context) {
		Date date = (Date) value;
		writer.setValue(format(this.dateformatter, date));
	}

	@Override
	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {
		try {
			return parse(this.dateformatter, reader.getValue());
		} catch (ParseException e) {
			try {
				return parse("yyyy-MM-dd", reader.getValue());
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
			throw new ConversionException(e.getMessage(), e);
		}
	}

	public static String format(String pattern, Date date) {
		if (date == null) {
			return "";
		} else {
			return new SimpleDateFormat(pattern).format(date);
		}
	}

	public static Date parse(String pattern, String text) throws ParseException {
		if(text==null||"".equals(text.trim())||"null".equals(text.trim().toLowerCase()))
		{
			return null;
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		return dateFormat.parse(text);
	}
}

 

    使用方法为:

   

 XStream xstream2 = new XStream(new DomDriver());
	   xstream2.registerConverter(new MyDateConverter());
	   xstream2.alias("Fault",Fault.class);
	   Fault fault2=(Fault) xstream2.fromXML(new File("f:/saveFile/tmp/fault2.xml"));
	   System.out.println(fault2);

 

    全文完。

  

你可能感兴趣的:(xstream)