gpt4 book ai didi

java - 如何创建没有入口的ElementMap?

转载 作者:太空宇宙 更新时间:2023-11-04 11:40:04 24 4
gpt4 key购买 nike

我需要使用 simlexml 序列化 Map 对象:

<attributes>
<name>name1</name>
<value>value1</value>
<name>name2</name>
<value>value2</value>
<name>name3</name>
<value>value3</value>
</attributes>

我尝试过这个:

@ElementMap(name = "attributes", key = "name", value = "value", inline = true, required = false)
private HashMap<String, String> attributes;

但结果看起来像:

   <entry>
<name>name1</name>
<value>value1</value>
</entry>
<entry>
<name>name2</name>
<value>value2</value>
</entry>
<entry>
<name>name3</name>
<value>value3</value>
</entry>

是否可以使用 simplexml 创建我需要的元素?

最佳答案

正如runefist所指出的,将为这种类型生成入口标签。但您可以做什么:使用 Converter 自定义(反)序列化过程。 .

这是序列化的示例类:

@Root(name = "Example")
public class Example
{
@Element
@Convert(ExampleConverter.class)
private HashMap<String, String> attributes; // Will use the Converter instead

// ...

public static class ExampleConverter implements Converter<HashMap<String, String>>
{
@Override
public HashMap<String, String> read(InputNode node) throws Exception
{
// Implement if needed
}


@Override
public void write(OutputNode node, HashMap<String, String> value) throws Exception
{
value.forEach((k, v) -> {
try
{
node.getChild("name").setValue(k);
node.getChild("value").setValue(v);
}
catch( Exception ex )
{
// Handle Error
}
});
}

}
}

如果您还需要反序列化您的类,则只需实现 read() 方法。

最后,不要忘记启用AnnotationStrategy:

Serializer ser = new Persister(new AnnotationStrategy());
// ^^^^^^^^^^^^^^^^^^^^

这将生成以下输出:

<Example>
<attributes>
<name>name2</name>
<value>value2</value>
<name>name1</name>
<value>value1</value>
<name>name0</name>
<value>value0</value>
</attributes>
</Example>

关于java - 如何创建没有入口的ElementMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42900338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com