使用JAXB 转化bean(支持map对象)

jaxb可以使用XmlAdapter来定义复杂对象。
Map是我们经常用的对象所以下面演示下怎么使用
1、beans里面包含一个map对象,bean对象不发生变化
@XmlRootElement(name = "beans", namespace = "http://www.example.org/studyframework_0.1")
@XmlAccessorType(XmlAccessType.NONE)
public class Beans {

	@XmlElement(name = "bean")
	@XmlJavaTypeAdapter(MapAdapter.class)
	private Map<String, Bean> beanMap;

	public Map<String, Bean> getBeanMap() {
		return beanMap;
	}

	public void setBeanMap(Map<String, Bean> beanMap) {
		this.beanMap = beanMap;
	}

}

2、添加MapAdapter对象
public class MapAdapter extends XmlAdapter<Bean[], Map<String, Bean>> {
	@Override
	public Bean[] marshal(Map<String, Bean> map) throws Exception {
		Bean[] Beans = new Bean[map.size()];
		int i = 0;
		Iterator<Entry<String, Bean>> it = map.entrySet().iterator();
		while (it.hasNext()) {
			Beans[i] = new Bean();
			Entry<String, Bean> entry = it.next();
			Beans[i].setId(entry.getKey());
			Beans[i].setClassName(entry.getValue().getClassName());
			i++;
		}
		return Beans;
	}

	@Override
	public Map<String, Bean> unmarshal(Bean[] arg0) throws Exception {
		Map<String, Bean> map = new HashMap<String, Bean>();
		for (Bean bean : arg0) {
			Bean newBean = new Bean();
			newBean.setId(bean.getId());
			newBean.setClassName(bean.getClassName());
			map.put(bean.getId(), newBean);
		}
		return map;
	}
}

这个类就可以使用户自己定义复杂对象,简单说明下
先说下这个范式
XmlAdapter<Bean[], Map<String, Bean>>
第1个Bean代表生成xml对象
MAP<String,Bean>代表从xml获取回来的对象
marshal方法就是把MAP对象转化为Bean[]
unmarshal把xml中的Bean[]转化为Map对象

3、调用方法如下
	@Test
	public void testMarshallerByJaxb() throws Exception {
		Beans beans = new Beans();
		HashMap<String, Bean> map = new HashMap<String, Bean>();
		Bean beanOne = new Bean();
		beanOne.setClassName("testClassOne");
		beanOne.setId("testIdOne");
		Bean beanTwo = new Bean();
		beanTwo.setClassName("testClassTwo");
		beanTwo.setId("testIdTwo");
		map.put("testIdOne", beanOne);
		map.put("testIdTwo", beanTwo);
		beans.setBeanMap(map);
		XMLTransformed.marshallerByJaxb("test.xml", beans, Beans.class);
	}

	public void testUnmarshallerByJaxb() throws Exception {
		Beans actual = (Beans) XMLTransformed.unmarshallerByJaxb("test.xml", Beans.class);
		Assert.assertEquals("testClassOne", actual.getBeanMap().get("testIdOne").getClassName());
	}

你可能感兴趣的:(bean)