用简单的xml序列化时间单位

toiithl6  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(495)

如何使用简单的xml库(版本2.6.5/2.6.6)序列化java.util.concurrent.timeunit?
下面是我要序列化的类:

@Root(name="settings")
public class Config
{
    // some more code

    @Element(name="timeunit", required=true)
    private static final TimeUnit timeunit = TimeUnit.SECONDS;

    // some more code
}

使用简单:

File f = // ...
Config cfg = new Config();
Serializer ser = new Persister();

ser.write(cfg, f);

我得到一个例外:

org.simpleframework.xml.transform.TransformException: Transform of class java.util.concurrent.TimeUnit$4 not supported

到目前为止,我测试了其他注解,比如@default,但问题是一样的。想知道为什么simple在时间单位上有问题-所有其他类型(类/原语类型)都可以正常工作。

vfwfrxfs

vfwfrxfs1#

下面是一个可能的解决方案:
注解:

@Element(name="timeunit", required=true)
@Convert(TimeUnitConverter.class)
private static final TimeUnit timeunit = TimeUnit.SECONDS;

转换器:

public class TimeUnitConverter implements Converter<TimeUnit>
{
    @Override
    public TimeUnit read(InputNode node) throws Exception
    {
        return TimeUnit.valueOf(node.getValue().toUpperCase());
    }

    @Override
    public void write(OutputNode node, TimeUnit value) throws Exception
    {
        node.getAttributes().remove("class"); /* Not required */
        node.setValue(value.toString().toLowerCase());
    }

}

相关问题