您可以在两种方法之间进行选择,如类似问题Serialization third-party classes with Simple XML (org.simpleframework.xml) 中所述:
我不知道每个比较的优缺点。但我确实知道如何实现 Transform 方法。为此,请继续阅读。
变换方法
需要三件:
-
Transform interface 的实现。
-
Matcher interface 的实现。
- 一个 RegistryMatcher 实例,其中 Transform 实现映射到它处理的数据类型。
所有这三个都是transform package 的一部分。
我建议将您的实现放在项目中的“转换器”包中。
转换实现
您的 Transform 实现可能如下所示。
这里的实现很简单。它假定您希望输出是由 DateTime 的 toString 方法生成的默认 ISO 8601 字符串。它假定每个文本输入都与DateTime 构造函数中的默认解析器兼容。要处理其他格式,定义一堆DateTimeFormatter 实例,对每个实例依次调用parseDateTime 方法,直到格式化程序成功而不抛出IllegalArgumentException。另一件要考虑的事情是时区;您可能希望将时区强制为 UTC 或类似的。
package com.your.package.converters.simplexml;
import org.joda.time.DateTime;
import org.simpleframework.xml.transform.Transform;
import org.slf4j.LoggerFactory;
/**
*
* © 2014 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for such usage and its consequences.
*/
public class JodaTimeDateTimeTransform implements Transform<DateTime>
{
//static final org.slf4j.Logger logger = LoggerFactory.getLogger( JodaTimeDateTimeTransform.class );
@Override
public DateTime read ( String input ) throws Exception
{
DateTime dateTime = null;
try {
dateTime = new DateTime( input ); // Keeping whatever offset is included. Not forcing to UTC.
} catch ( Exception e ) {
//logger.debug( "Joda-Time DateTime Transform failed. Exception: " + e );
}
return dateTime;
}
@Override
public String write ( DateTime dateTime ) throws Exception
{
String output = dateTime.toString(); // Keeping whatever offset is included. Not forcing to UTC.
return output;
}
}
匹配器实现
Matcher 实现快速简单。
package com.your.package.converters.simplexml;
import org.simpleframework.xml.transform.Transform;
import org.simpleframework.xml.transform.Matcher;
/**
*
* © 2014 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for such usage and its consequences.
*/
public class JodaTimeDateTimeMatcher implements Matcher
{
@Override
public Transform match ( Class classType ) throws Exception
{
// Is DateTime a superclass (or same class) the classType?
if ( org.joda.time.DateTime.class.isAssignableFrom( classType ) ) {
return new JodaTimeDateTimeTransform();
}
return null;
}
}
注册表
将这些付诸实施意味着使用注册表。
RegistryMatcher matchers = new RegistryMatcher();
matchers.bind( org.joda.time.DateTime.class , JodaTimeDateTimeTransform.class );
// You could add other data-type handlers, such as the "YearMonth" class in Joda-Time.
//matchers.bind( org.joda.time.YearMonth.class , JodaTimeYearMonthTransform.class );
Strategy strategy = new AnnotationStrategy();
Serializer serializer = new Persister( strategy , matchers );
然后以通常的方式继续使用理解 Joda-Time 类型的序列化程序。