我有XML:
<?xml version="1.0" encoding="UTF-8"?>
<addresses xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation='schema_task1_1.xsd'>
<address>
<name>Bill</name>
<city>NewYork</city>
<street>First</street>
<phone type='mobile'>+19139130000</phone>
<documents>
<document type='driving_permit'>9045798749</document>
<document type='passport'>3451231231</document>
</documents>
</address>
<address>
...
</address>
</addresses>
Java类:
@Root(name = "addresses")
public class Addresses {
@ElementList(inline = true, entry = "address", required = false, type = Address.class)
private List<Address> addresses = new ArrayList<Address>();
public class Address {
@Element(required = false)
private String name;
@Element(required = false)
private String city;
@Element(required = false)
private String street;
@ElementMap(entry = "phone", key = "type", attribute = true, inline = true)
private Map<String, String> phones;
@ElementMap(entry = "documents", key = "type", attribute = true, inline = true)
private Map<String, String> documents = new HashMap<String, String>();
除documents
外,所有字段都反序列化成功。尝试反序列化时始终为null
。我很瘦我在@ElementMap
注释中有错误,但我不知道到底是什么。我做错了什么?
PS。我无法更改对象结构,因为它被另一个解析器使用。
答案 0 :(得分:1)
您必须创建一个中间类来处理“文档”。 该类将包含“文档”的地图:
class Address {
...
@Element(required = false)
private Documents documents;
}
class Documents {
@ElementMap(entry = "document", key = "type", attribute = true, inline = true)
private Map<String, String> documents = new HashMap<String, String>();
}
答案 1 :(得分:0)
我解决了我的问题,但不太好。如果你知道更好的解决方案,请告诉我。
我刚刚修复了document
Map
的注释,并添加了uselessVariable
注释。它有效并且不会破坏旧代码。
UPD。我发现更好的解决方案添加了@Path
注释。
@Root(name = "addresses")
public class Addresses {
@ElementList(inline = true, entry = "address", required = false, type = Address.class)
private List<Address> addresses = new ArrayList<Address>();
public class Address {
@Element(required = false)
private String name;
@Element(required = false)
private String city;
@Element(required = false)
private String street;
@ElementMap(entry = "phone", key = "type", attribute = true, inline = true)
private Map<String, String> phones;
@Path("./documents")
@ElementMap(entry = "document", key = "type", attribute = true, inline = true) //changed this line
private Map<String, String> documents = new HashMap<String, String>();