XmlAdapter怎么用

weixin_45433596 2019-07-20 11:02:53
各位大佬,我在学习XmlAdapter怎么用。
下面的代码只是把HashMap绑定成一个List。
帮我看看下面代码哪里不对?为什么它输出的是空的mypeople?
输出如下

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<MyRootElement>
<mypeople/>
</MyRootElement>

代码如下

package com.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement(name="MyRootElement")
@XmlAccessorType(XmlAccessType.FIELD)
public class XmlAdapter2 {
//@XmlElement
//@XmlElementWrapper(name="PeopleWrapper")
@XmlJavaTypeAdapter(MyMapAdapter.class)
private Map<Integer, String> mypeople;


public static void main(String[] args) throws Exception {
XmlAdapter2 root = new XmlAdapter2();

root.getPeople().put(1, "One");
root.getPeople().put(2, "Two");
root.getPeople().put(3, "Three");

System.out.println(root.getPeople().size());

JAXBContext context = JAXBContext.newInstance(XmlAdapter2.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(root, System.out);
}


public Map<Integer, String> getPeople() {
if (mypeople == null) {
mypeople = new HashMap<>();
}
return mypeople;
}

}

class People {
@XmlAttribute
private Integer id;
@XmlValue
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

class PeopleList {
private List<People> peopleList;

public List<People> getPeopleList() {
if (peopleList == null) {
peopleList = new ArrayList<>();
}
System.out.println(peopleList.size());
return peopleList;
}

}
class MyMapAdapter extends javax.xml.bind.annotation.adapters.XmlAdapter<PeopleList, Map<Integer, String>> {

@Override
public PeopleList marshal(Map<Integer, String> peopleMap) throws Exception {

PeopleList peopleList = new PeopleList();
for (Integer key: peopleMap.keySet()) {
People p = new People();
p.setId(key);
p.setName(peopleMap.get(key));
peopleList.getPeopleList().add(p);
}
System.out.println(peopleList.getPeopleList().size());
return peopleList;
}

@Override
public Map<Integer, String> unmarshal(PeopleList peopleList) throws Exception {
Map<Integer, String> map = new HashMap<>();
for (People p: peopleList.getPeopleList()) {
map.put(p.getId(), p.getName());
}
return map;
}

}

...全文
63 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,625

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧