java对象转xml序列化
时间: 2023-08-31 12:09:57 浏览: 158
java对象转化xml.
3星 · 编辑精心推荐
Java对象可以通过序列化的方式转换为XML格式的数据,常用的方式有以下两种:
1. 使用Java自带的XMLEncoder和XMLDecoder类进行序列化和反序列化。
示例代码:
```java
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
public class XmlSerializer {
public static <T> String serialize(T object) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder(baos);
encoder.writeObject(object);
encoder.close();
try {
return baos.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static <T> T deserialize(String xml, Class<T> clazz) {
ByteArrayInputStream bais;
try {
bais = new ByteArrayInputStream(xml.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
XMLDecoder decoder = new XMLDecoder(bais);
Object object = decoder.readObject();
decoder.close();
return clazz.cast(object);
}
}
```
使用示例:
```java
class User {
private String name;
private int age;
public User() {}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
User user = new User("Tom", 18);
String xml = XmlSerializer.serialize(user);
System.out.println(xml);
User newUser = XmlSerializer.deserialize(xml, User.class);
System.out.println(newUser.getName() + ", " + newUser.getAge());
}
}
```
2. 使用第三方库,如Jackson、XStream等。这些库可以更灵活地控制序列化和反序列化的过程,并支持更多的数据格式转换。
示例代码(使用Jackson库):
```java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class XmlSerializer {
private static final ObjectMapper objectMapper = new XmlMapper();
public static <T> String serialize(T object) {
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
public static <T> T deserialize(String xml, Class<T> clazz) {
try {
return objectMapper.readValue(xml, clazz);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
}
```
使用示例同上。
阅读全文