我想原因是,Simple不能转换 HashMaps。
如果我运行此代码...
Map<String, Object> map = new HashMap<>();
map.put("a", "b");
map.put("c", 3);
map.put("d", new Date());
ser.write(map, new File("test2.xml"));
...我得到以下异常:
org.simpleframework.xml.transform.TransformException: Transform of class java.util.HashMap not supported
现在,这是我为使您的课程序列化所做的工作:
我写了一个转换器,用于转换Settings
.
Converter
班级:
public class SettingsConverter implements Converter<Settings>
{
private Transformer transformer;
public SettingsConverter()
{
this.transformer = new Transformer(new RegistryMatcher());
}
@Override
public Settings read(InputNode node) throws Exception
{
Settings settings = new Settings();
InputNode child = node.getNext();
while( child != null )
{
final String key = child.getAttribute("key").getValue();
final Class c = Class.forName(child.getAttribute("class").getValue());
settings.put(key, transformer.read(child.getAttribute("value").getValue(), c));
child = node.getNext();
}
return settings;
}
@Override
public void write(OutputNode node, Settings value) throws Exception
{
for( Map.Entry<String, Object> entry : value.entrySet() )
{
OutputNode child = node.getChild("setting");
child.setAttribute("key", entry.getKey());
child.setAttribute("class", entry.getValue().getClass().getName());
child.setAttribute("value", transformer.write(entry.getValue(), entry.getValue().getClass()));
}
}
}
Settings
班级:
@Root()
@Convert(value=SettingsConverter.class)
public class Settings extends HashMap<String, Object>
{
// ...
}
测试:
final File testFile = new File("test.xml");
Settings settings = new Settings();
settings.put("a", "b");
settings.put("c", 3);
settings.put("d", new Date());
// Serialize - make shure you use an AnnotationStrategy here
Serializer ser = new Persister(new AnnotationStrategy());
ser.write(settings, testFile);
// Deserialize
Settings in = ser.read(Settings.class, testFile);
System.out.println(settings.equals(in));
文件 test.xml:
<settings>
<setting key="d" class="java.util.Date" value="2012-08-28 17:15:13.152 MESZ"/>
<setting key="c" class="java.lang.Integer" value="3"/>
<setting key="a" class="java.lang.String" value="b"/>
</settings>
我想有更好的方法(如果不是更多)可以做到这一点,但也许这会有所帮助。
还有一点,@Default
注解在这里不起作用(异常),可能解决这个问题可能会解决整个问题