考虑以下Map结构(JSON用于简化):
{
"key1": "value1",
"key2": "value2"
}考虑到映射是Parent的类变量,使用Java框架,我如何转换为以下SimpleXML。
<Parent>
<key1>value1</key1>
<key2>value2</key2>
</Parent>我看过关于内联映射等方面的SimpleXML教程,但它并没有解决问题。我想我需要实现某种自定义的序列化程序。?
发布于 2015-02-19 21:12:46
据我所知,正确的结构应该是:
<Parent>
<mapFieldOfTheParentClass>
<key1>value1</key1>
<key2>value2</key2>
</mapFieldOfTheParentClass>
</Parent>这是因为您的类可能有一个名为"key1“的字段,并且无法将其与map的键区分开来。但是,如果您确定您想要自己的结构,那么只要不发生冲突,定制的序列化程序就可以工作。
发布于 2015-02-19 22:30:31
我需要实现某种自定义的序列化程序。
在这种情况下,您将无法绕过这一点。但幸运的是,它并不复杂。
下面是一个例子:
@Root(name = "Parent")
@Convert(Example.ParentConverter.class)
public class Example
{
private Map<String, String> values;
// ...
static class ParentConverter implements Converter<Example>
{
@Override
public Example read(InputNode node) throws Exception
{
Example value = new Example();
value.values = new HashMap<>();
InputNode next;
while( ( next = node.getNext() ) != null )
{
value.values.put(next.getName(), next.getValue());
}
return value;
}
@Override
public void write(OutputNode node, Example value) throws Exception
{
// Implement to support writing too
throw new UnsupportedOperationException("Not supported yet.");
}
}
}@Convert需要例如。一个AnnotationStrategy
Serializer ser = new Persister(new AnnotationStrategy());
Example e = ser.read(Example.class, xml); // xml = input xml编辑:
仅映射字段转换器的可能实现:
@Override
public void write(OutputNode node, Map<String, String> value) throws Exception
{
final OutputNode parent = node.getParent();
if( !value.isEmpty() )
{
boolean first = true;
for( Map.Entry<String, String> e : value.entrySet() )
{
if( first == true )
{
node.setName(e.getKey());
node.setValue(e.getValue());
// Remove generated 'class' attribute for collections
node.getAttributes().remove("class");
first = false;
}
else
{
parent.getChild(e.getKey()).setValue(e.getValue());
}
}
}
else
{
// Handle empty maps
}
}https://stackoverflow.com/questions/28607126
复制相似问题