java利用JAXB实现对象和xml互相转换方法与实例详解
1、JAXB应用场景
在使用WebService实现数据上传下载,数据查询时,可以利用JAXB实现java实体类和xml互相转换
2、Demo
2.1 student.java 实体类
包含list(set同理)、map、Teacher、Date 类型的属性
package jaxb; import java.util.Date; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; @XmlType(propOrder={"id","name","age","birthDay","list","teacher","map"}) //指定序列成的xml节点顺序 @XmlAccessorType(value=XmlAccessType.FIELD) //访问类型改为字段 @XmlRootElement public class Student { @XmlElement private String id; @XmlElement private String name; @XmlElement private int age; @XmlJavaTypeAdapter(value=DateAdapter.class) @XmlElement private Date birthDay; @XmlElement private List<Teacher> list; @XmlElement private Teacher teacher; @XmlJavaTypeAdapter(value=MapAdapter.class) // @XmlElementWrapper(name="role") @XmlElement private Map map; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } public List getList() { return list; } public void setList(List list) { this.list = list; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + ", birthDay=" + birthDay + ", list=" + list + ", teacher=" + teacher + ", map=" + map + "]"; } }
2.2 Teacher.java类
注意:Teacher 类不包含@XmlRootElement节点,因为目的是转成一个XML文档,根节点只有一个
package jaxb; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(value=XmlAccessType.FIELD) @XmlType(propOrder={"id","name","age"}) public class Teacher { @XmlElement private int id; @XmlElement private String name; @XmlElement private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Teacher(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } public Teacher() { } @Override public String toString() { return "Teacher [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
2.3 DateApdapter.java
自定义时间适配器类
在java实体类序列化xml日期时,需要对时间进行自定义转换,jaxb提供了XmlAdapter,只要实现它后就可以自定义日期适配器
package jaxb; import java.text.SimpleDateFormat; import java.util.Date; import javax.xml.bind.annotation.adapters.XmlAdapter; public class DateAdapter extends XmlAdapter<String, Date> { //反序列化成日期对象Date @Override public Date unmarshal(String str) throws Exception { SimpleDateFormat format = getSimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return str==null ? null:format.parse(str); } //序列化成xmL @Override public String marshal(Date date) throws Exception { SimpleDateFormat format = getSimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return date==null ? "":format.format(date); } private SimpleDateFormat getSimpleDateFormat(String pattern){ SimpleDateFormat format = new SimpleDateFormat(pattern); return format; } }
2.4 Entry.java类
用来封装map元素
package jaxb; public class Entry { private String key; private Object value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } }
2.5、MapAdpter.java
map 转换器
本人在写map转换器之后,感觉跟jaxb 默认序列化的方式没什么区别,目前还不知道在javb中需不需要特地写map转换器,希望有经验的朋友分享下
package jaxb; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.adapters.XmlAdapter; public class MapAdapter extends XmlAdapter<MapAdapter.AdapterMap,Map<String,Object>> { public static class AdapterMap { public List<Entry> entry =new ArrayList<Entry>(); } /** * 功能:xml->Map<String,Object> * @param adapterMap * @return * @throws Exception */ @Override public Map<String, Object> unmarshal(AdapterMap adapterMap) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); List entry = adapterMap.entry; for(Entry en:adapterMap.entry){ map.put(en.getKey(), en.getValue()); } return map; } /** * 功能:map<String,Object> -> xml */ @Override public AdapterMap marshal(Map<String, Object> map) throws Exception { AdapterMap adapterMap = new AdapterMap(); for (Map.Entry<String, Object> entry : map.entrySet()) { Entry entry2 = new Entry(); entry2.setKey(entry.getKey()); entry2.setValue(entry.getValue()); adapterMap.entry.add(entry2); } return adapterMap; } }
2.6 测试类 JaxbDemo.java
package jaxb; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; public class JaxbDemo { public static void main(String[] args) { Student stu = new Student(); stu.setId("1"); stu.setName("罗志茂"); stu.setAge(25); stu.setBirthDay(new Date()); //list集合,set集合一样 ArrayList<Teacher> list = new ArrayList<Teacher>(); list.add(new Teacher(2,"曾利梅",22)); list.add(new Teacher(3,"黄伙林",22)); list.add(new Teacher(4,"潘志华",22)); stu.setList(list); //在javaBean中添加javaBean Teacher teacher = new Teacher(1,"宋瑶",22); stu.setTeacher(teacher); //添加map集合 HashMap<Object, Object> map = new HashMap<>(); map.put("1", "林乐贤"); map.put("2", "德甲"); stu.setMap(map); try { JAXBContext context = JAXBContext.newInstance(Student.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK"); //marshaller.marshal(stu, System.out); StringWriter writer = new StringWriter(); marshaller.marshal(stu, writer); System.out.println(writer.toString()); //反序列化 Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader reader = new StringReader(writer.toString()); Student stu2 = (Student) unmarshaller.unmarshal(reader); System.out.println("stu2"+stu2); } catch (JAXBException e) { e.getMessage(); e.printStackTrace(); } } }
3.测试结果
<?xml version="1.0" encoding="GBK" standalone="yes"?> <student> <id>1</id> <name>罗志茂</name> <age>25</age> <birthDay>2016-08-18 23:07:26</birthDay> <list> <id>2</id> <name>曾利梅</name> <age>22</age> </list> <list> <id>3</id> <name>黄伙林</name> <age>22</age> </list> <list> <id>4</id> <name>潘志华</name> <age>22</age> </list> <teacher> <id>1</id> <name>宋瑶</name> <age>22</age> </teacher> <map> <entry> <key>2</key> <value xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">德甲</value> </entry> <entry> <key>1</key> <value xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">林乐贤</value> </entry> </map> </student>
stu2Student [id=1, name=罗志茂, age=25, birthDay=Thu Aug 18 23:07:26 CST 2016, list=[Teacher [id=2, name=曾利梅, age=22], Teacher [id=3, name=黄伙林, age=22], Teacher [id=4, name=潘志华, age=22]], teacher=Teacher [id=1, name=宋瑶, age=22], map={2=德甲, 1=林乐贤}]
更多关于java利用JAXB实现对象和xml互相转换方法与实例请查看下面的相关链接
阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机