Skip to main content
 首页 » 编程设计

Jackson实现xml序列化和反序列化

2022年07月19日184dyllove98

Jackson实现xml序列化和反序列化

本文介绍Jackson 2.X中提供的xml序列化功能。仅介绍基本操作,不涉及复杂和自定义功能。

1. XmlMapper对象

XmlMapper是Jackson 2.x中提供我们实现xml序列化的主要类,因此首先需要创建其实例:

XmlMapper mapper = new XmlMapper(); 

想要maven依赖脚本为:

<dependency> 
    <groupId>com.fasterxml.jackson.dataformat</groupId> 
    <artifactId>jackson-dataformat-xml</artifactId> 
    <version>2.9.8</version> 
</dependency> 

2. 序列化至xml

XmlMapper是json序列化ObjectMapper类的子类,对父类增加了一些关于xml规范的调整。下面关于如何使用其实现序列化,首先让我们定义一个示例类:

class SimpleBean { 
    private int x = 1; 
    private int y = 2; 
     
    //standard setters and getters 
}    

2.1. 序列化为xml字符串

我们首先序列化java对象为xml字符串:

@Test 
public void whenJavaSerializedToXmlStr_thenCorrect() throws JsonProcessingException { 
    XmlMapper xmlMapper = new XmlMapper(); 
    String xml = xmlMapper.writeValueAsString(new SimpleBean()); 
    assertNotNull(xml); 
} 

生成结果为:

<SimpleBean> 
    <x>1</x> 
    <y>2</y> 
</SimpleBean> 

2.2. 序列化为xml文件

下面序列化为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文件的内容如下:

<SimpleBean> 
    <x>1</x> 
    <y>2</y> 
</SimpleBean> 

3. 反序列化xml至Java

本节说明如何从xml中获取java对象。

3.1. 从xml字符串反序列化

和序列化一样,我们可以从xml字符串反序列化获得java对象:

@Test 
public void whenJavaGotFromXmlStr_thenCorrect() throws IOException { 
    XmlMapper xmlMapper = new XmlMapper(); 
    SimpleBean value 
      = xmlMapper.readValue("<SimpleBean><x>1</x><y>2</y></SimpleBean>", SimpleBean.class); 
    assertTrue(value.getX() == 1 && value.getY() == 2); 
} 

3.2. 从xml文件反序列化

同理,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(); 
} 

4. 处理大写元素

本节描述下序列化或反序列化过程中如何处理大写元素。

4.1. 从xml字符串反序列化

假定有下面xml字符串,其中一个字段值为大写:

<SimpleBeanForCapitalizedFields> 
    <X>1</X> 
    <y>2</y> 
</SimpleBeanForCapitalizedFields> 

为了正确处理大写元素,需要在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( 
      "<SimpleBeanForCapitalizedFields><X>1</X><y>2</y></SimpleBeanForCapitalizedFields>", 
      SimpleBeanForCapitalizedFields.class); 
    assertTrue(value.getX() == 1 && value.getY() == 2); 
} 

4.2. 序列化为xml字符串

通过增加注解@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); 
} 

5. 列表属性

5.1. 序列化列表属性

XmlMapper 能够序列化整个java bean至xml文档。下面说明如何序列化嵌套对象和数组。

我们需求是序列号Person对象,嵌套了Address对象至xml,最终xml如下:

<Person> 
    <firstName>Rohan</firstName> 
    <lastName>Daye</lastName> 
    <phoneNumbers> 
        <phoneNumbers>9911034731</phoneNumbers> 
        <phoneNumbers>9911033478</phoneNumbers> 
    </phoneNumbers> 
    <address> 
        <streetName>Name1</streetName> 
        <city>City1</city> 
    </address> 
    <address> 
        <streetName>Name2</streetName> 
        <city>City2</city> 
    </address> 
</Person> 

我们看电话号码被phoneNumbers元素包装,而地址没有。我们可以通过@JacksonXMLElementWrapper 注解表达这种差异:

public final class Person { 
    private String firstName; 
    private String lastName; 
    private List<String> phoneNumbers = new ArrayList<>(); 
    @JacksonXmlElementWrapper(useWrapping = false) 
    private List<Address> 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 = "<Person>...</Person>"; 
  
@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());  
} 

5.2. 反序列化列表属性

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()); 
} 

6. 总结

本文简单描述如何序列化和反序列化xml。也提及如何解决大写元素和负责的嵌套对象问题。


本文参考链接:https://blog.csdn.net/neweastsun/article/details/100044167