1、应用场景

在使用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=林乐贤}]

利用JAXB实现java实体类和xml互相转换的更多相关文章

  1. java 实体类中日期格式转换

    @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss&quo ...

  2. xml文档的解析并通过工具类实现java实体类的映射:XML工具-XmlUtil

    若有疑问,可以联系我本人微信:Y1141100952 声明:本文章为原稿,转载必须说明 本文章地址,否则一旦发现,必追究法律责任 1:本文章显示通过 XML工具-XmlUtil工具实现解析soap报文 ...

  3. 利用在线工具根据JSon数据自动生成对应的Java实体类

    如果你希望根据JSon数据自动生成对应的Java实体类,并且希望能进行变量的重命名,那么“JSON To Java”一定适合你.(下面的地址需要FQ) https://jsontojava.appsp ...

  4. MyEclipse 利用反向功能生成Java 实体类

    1.Window -> Open Perspective -> MyEclipse Database Explorer 到DB Broswer界面 2.右键 -> New,新建一个数 ...

  5. 简单实体类和xml文件的相互转换

    最近写一个题目,要求将一组员工实体类转换成xml文件,或将xml文件转换成一组实体类.题目不难,但写完感觉可以利用泛型和反射将任意一个实体类和xml文件进行转换.于是今天下午立马动手 试了下,做了个简 ...

  6. 实体类转xml

    看项目中需要实体类转xml,大家是拼接的.感觉可以利用反射实现.于是写了下 代码如下 package com.kevin.util; import org.springframework.util.O ...

  7. Android利用反射机制为实体类属性赋值

    在做android项目时,有时会遇到从网络上获取json类型数据,赋值给实体类,实体类属性少可以一个一个的赋值,如果实体类有很多属性,赋值可能就要耗很长的功夫了,幸好Java给我们提供了反射机制.下面 ...

  8. 我写了一个java实体类,implements了Serializable接口,然后我如何让serialversionUID自动生成

    写了一个java实体类,implements了Serializable接口,让serialversionUID自动生成方法: 1.点击类旁边的警告符号: 2.选择Add generated seria ...

  9. C#实体类生成XML与XML Schema文档

    一.实体类生成XML private void CreateXML() { Type[] objType = DBEntityRegst(); foreach (var item in objType ...

随机推荐

  1. 直播CDN架构随想

    互联网内容载体变迁历程,文字--图片/声音--视频--VR/AR----从直播1.0秀场时代(YY).2.0游戏直播(斗鱼.虎牙.熊猫)到如今全民直播3.0泛生活娱乐时代(映客.花椒),国外直播App ...

  2. maven 的各种命令

    mvn clean : 清理旧的文件 mvn clean compile :  清理 .编译 mvn clean test :       清理 .编译 .测试 mvn clean package : ...

  3. delphi 线程教学第四节:多线程类的改进

    第四节:多线程类的改进   1.需要改进的地方   a) 让线程类结束时不自动释放,以便符合 delphi 的用法.即 FreeOnTerminate:=false; b) 改造 Create 的参数 ...

  4. Docker报错 WARNING: IPv4 forwarding is disabled. Networking will not work.

    问题:创建容器的时候报错WARNING: IPv4 forwarding is disabled. Networking will not work. # docker run -it -p 3000 ...

  5. Spring Boot(一)

    (一)如何使用IDEA新建一个Spring Boot项目 https://www.cnblogs.com/wmyskxz/p/9010832.html

  6. ie9上传后下载json

    1.保持后台控制器返回的数据为字符串格式 2.js:dataType类型保持为html格式 dataType: 'html',//默认就是html类型,不写对火狐有影响 3.将上传后后台返回的字符串转 ...

  7. MFC控件第一讲.DC编程

    MFC控件第一讲.DC编程 一丶简介 什么是DC,DC有什么用. DC成为设备描述符表. DC的作用就是可以进行绘制. 比如我们的窗口都是绘制出来的.  DC可以简单理解为.没一个窗口程序都有一块内存 ...

  8. hdu3966 树链剖分点权模板+线段树区间更新/树状数组区间更新单点查询

    点权树的模板题,另外发现树状数组也是可以区间更新的.. 注意在对链进行操作时方向不要搞错 线段树版本 #include<bits/stdc++.h> using namespace std ...

  9. zabbix3.4 实现sendEmail邮件报警

    zabbix3.4实现sendEmail邮件报警 转发:https://www.cnblogs.com/pythonal/p/7813948.html sendEmail是一个轻量级,命令行的SMTP ...

  10. vSphere client 登陆ESXI主机“您无权登录次服务器”

    vCenter安装在虚拟机上,安装好后想调整下内存,直接把虚拟机关闭了电源,突然一想服务器都被我关了,还拿什么修改内存,完蛋! 突然想起,在使用vCenter之前,都是用vsphere client ...