com.fasterxml.jackson.dataformat.xml.XmlMapper把对象转换xml格式,属性放到标签<>里边
之前从没用过xml和对象相互转换,最近项目接了政府相关的。需要用xml格式数据进行相互转换。有些小问题,困扰了我一下下。
1.有些属性需要放到标签里边,有的需要放到标签子集。
2.xml需要加<?xml version="1.0" encoding="utf-8"?>头。
属性放到标签里边设置,isAttribute = true,代码如下:
package com.huateng.gongan.job.xml.bean;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;public class Add {@JacksonXmlProperty(localName = "key",isAttribute = true)private String key;@JacksonXmlProperty(localName = "value",isAttribute = true)private String value;public Add(String key, String value) {this.key = key;this.value = value;}public Add() {}public String getKey() {return key;}public void setKey(String key) {this.key = key;}public String getValue() {return value;}public void setValue(String value) {this.value = value;}public static void main(String[] args) throws JsonProcessingException {Add add = new Add("123","456");XmlMapper xmlMapper = new XmlMapper();String xml = xmlMapper.writeValueAsString(add);System.out.println(xml);}
}
输出样式:
<Add><key>123</key><value>456</value></Add>
属性放到标签子集设置,代码如下:
package com.huateng.gongan.job.xml.bean;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;public class Add {@JacksonXmlProperty(localName = "key")private String key;@JacksonXmlProperty(localName = "value")private String value;public Add(String key, String value) {this.key = key;this.value = value;}public Add() {}public String getKey() {return key;}public void setKey(String key) {this.key = key;}public String getValue() {return value;}public void setValue(String value) {this.value = value;}public static void main(String[] args) throws JsonProcessingException {Add add = new Add("123","456");XmlMapper xmlMapper = new XmlMapper();String xml = xmlMapper.writeValueAsString(add);System.out.println(xml);}
}
输出样式:
<add key="1" value="value1"/>
xml加<?xml version="1.0" encoding="utf-8"?>头,设置objectMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true),代码如下:
XmlMapper objectMapper = new XmlMapper();objectMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);objectMapper.writeValueAsString(configuration);