jackson 转换xml

    之前在网上看到jackson可以转成xml但一直也没有测试成功,今天测试通过了,测试代码如下(网上直接拿过来的):
	@Test
	public void writeObject2Xml() {
	    System.out.println("XmlMapper");
	    XmlMapper xml = new XmlMapper();
	    
	    try {
	        //javaBean转换成xml
	        //xml.writeValue(System.out, bean);
	        StringWriter sw = new StringWriter();
	        xml.writeValue(sw, bean);
	        System.out.println(sw.toString());
	        //List转换成xml
	        List<Account> list = new ArrayList<Account>();
	        list.add(bean);
	        list.add(bean);
	        System.out.println(xml.writeValueAsString(list));
	        
	        //Map转换xml文档
	        Map<String, Account> map = new HashMap<String, Account>();
	        map.put("A", bean);
	        map.put("B", bean);
	        System.out.println(xml.writeValueAsString(map));
	    } catch (JsonGenerationException e) {
	        e.printStackTrace();
	    } catch (JsonMappingException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

输出结果:
XmlMapper
<Account xmlns=""><id>1</id><name>haha</name><email>[email protected]</email><address>CHINA-BJ</address><birthday/></Account>
<ArrayList xmlns=""><id>1</id><name>haha</name><email>[email protected]</email><address>CHINA-BJ</address><birthday/></ArrayList><ArrayList><id>1</id><name>haha</name><email>[email protected]</email><address>CHINA-BJ</address><birthday/></ArrayList>
<HashMap xmlns=""><A><id>1</id><name>haha</name><email>[email protected]</email><address>CHINA-BJ</address><birthday/></A><B><id>1</id><name>haha</name><email>[email protected]</email><address>CHINA-BJ</address><birthday/></B></HashMap>


附件是用到的jar

ps:感觉生成的XML不是太好,目前还不知道怎么改一下头标签,尤其是ArrayList的XML结果

如果没有应用maven,可以到下面的地址下载用到的jar
https://oss.sonatype.org/index.html

你可能感兴趣的:(Jackson)