我想序列化一个用Simple扩展HashMap的元素。
@Root(name = "settings")
@ElementMap(entry="element", key="id", attribute=true, required=true, empty=true)
public class Settings extends HashMap<String, Object> {
...
每当我序列化它时,我都没有错误,但我也得到一个看起来像这样的空文件:
<settings/>
有没有办法在不创建内部对象的情况下执行此操作,然后必须将所有方法委托给它?
答案 0 :(得分:1)
我想原因是,简单无法转换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
现在,我正是为了让您的课程序列化而做的:
我写了Converter,用于转换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
注释在这里不起作用(例外),可能解决这个问题可以解决整个问题