本文介绍Jackson 2.X中提供的xml序列化功能。仅介绍基本操作,不涉及复杂和自定义功能。
XmlMapper是Jackson 2.x中提供我们实现xml序列化的主要类,因此首先需要创建其实例:
XmlMapper mapper = new XmlMapper();
想要maven依赖脚本为:
com.fasterxml.jackson.dataformat
jackson-dataformat-xml
2.9.8
XmlMapper是json序列化ObjectMapper类的子类,对父类增加了一些关于xml规范的调整。下面关于如何使用其实现序列化,首先让我们定义一个示例类:
class SimpleBean {
private int x = 1;
private int y = 2;
//standard setters and getters
}
我们首先序列化java对象为xml字符串:
@Test
public void whenJavaSerializedToXmlStr_thenCorrect() throws JsonProcessingException {
XmlMapper xmlMapper = new XmlMapper();
String xml = xmlMapper.writeValueAsString(new SimpleBean());
assertNotNull(xml);
}
生成结果为:
1
2
下面序列化为xml文件:
@Test
public void whenJavaSerializedToXmlFile_thenCorrect() throws IOException {
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(new File("simple_bean.xml"), new SimpleBean());
File file = new File("simple_bean.xml");
assertNotNull(file);
}
同样生成simple_bean.xml文件的内容如下:
1
2
本节说明如何从xml中获取java对象。
和序列化一样,我们可以从xml字符串反序列化获得java对象:
@Test
public void whenJavaGotFromXmlStr_thenCorrect() throws IOException {
XmlMapper xmlMapper = new XmlMapper();
SimpleBean value
= xmlMapper.readValue("1 2 ", SimpleBean.class);
assertTrue(value.getX() == 1 && value.getY() == 2);
}
同理,xml文件也能转换为Java对象。首先读文件至输入流,然后使用简单方法转换输入流至字符串,剩下工作和上节一样:
@Test
public void whenJavaGotFromXmlFile_thenCorrect() throws IOException {
File file = new File("simple_bean.xml");
XmlMapper xmlMapper = new XmlMapper();
String xml = inputStreamToString(new FileInputStream(file));
SimpleBean value = xmlMapper.readValue(xml, SimpleBean.class);
assertTrue(value.getX() == 1 && value.getY() == 2);
}
inputStreamToString方法代码如下:
public String inputStreamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
本节描述下序列化或反序列化过程中如何处理大写元素。
假定有下面xml字符串,其中一个字段值为大写:
1
2
为了正确处理大写元素,需要在x字段上增加@JsonProperty("X")
注解:
class SimpleBeanForCapitalizedFields {
@JsonProperty("X")
private int x = 1;
private int y = 2;
// standard getters, setters
}
这时则可以正确反序列化xml字符串为java对象:
@Test
public void whenJavaGotFromXmlStrWithCapitalElem_thenCorrect() throws IOException {
XmlMapper xmlMapper = new XmlMapper();
SimpleBeanForCapitalizedFields value
= xmlMapper.readValue(
"1 2 ",
SimpleBeanForCapitalizedFields.class);
assertTrue(value.getX() == 1 && value.getY() == 2);
}
通过增加注解@JsonProperty
,可以正确序列化java对象至包括大写元素的xml字符串:
@Test
public void whenJavaSerializedToXmlFileWithCapitalizedField_thenCorrect()
throws IOException {
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(new File("target/simple_bean_capitalized.xml"),
new SimpleBeanForCapitalizedFields());
File file = new File("target/simple_bean_capitalized.xml");
assertNotNull(file);
}
XmlMapper 能够序列化整个java bean至xml文档。下面说明如何序列化嵌套对象和数组。
我们需求是序列号Person对象,嵌套了Address对象至xml,最终xml如下:
Rohan
Daye
9911034731
9911033478
Name1
City1
Name2
City2
我们看电话号码被phoneNumbers元素包装,而地址没有。我们可以通过@JacksonXMLElementWrapper 注解表达这种差异:
public final class Person {
private String firstName;
private String lastName;
private List phoneNumbers = new ArrayList<>();
@JacksonXmlElementWrapper(useWrapping = false)
private List address = new ArrayList<>();
//standard setters and getters
}
实际上,也能改变包装元素的名称,如:@JacksonXmlElementWrapper(localName = ‘phoneNumbers’)
。或者如果不需要包装元素,也可以使用注解禁用:@JacksonXmlElementWrapper(useWrapping = false)
。
下面定义Address类:
public class Address {
String streetName;
String city;
//standard setters and getters
}
Jackson负责下面的工作,和前面一样仅需要简单调用writeValue方法:
private static final String XML = "... ";
@Test
public void whenJavaSerializedToXmlFile_thenSuccess() throws IOException {
XmlMapper xmlMapper = new XmlMapper();
Person person = testPerson(); // test data
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
xmlMapper.writeValue(byteArrayOutputStream, person);
assertEquals(XML, byteArrayOutputStream.toString());
}
Jackson也可以读包括list对象的xml文档。假如读取前面的xml,使用readValue方法:
@Test
public void whenJavaDeserializedFromXmlFile_thenCorrect() throws IOException {
XmlMapper xmlMapper = new XmlMapper();
Person value = xmlMapper.readValue(XML, Person.class);
assertEquals("City1", value.getAddress().get(0).getCity());
assertEquals("City2", value.getAddress().get(1).getCity());
}
本文简单描述如何序列化和反序列化xml。也提及如何解决大写元素和负责的嵌套对象问题。