一.Jaxb处理java对象和xml之间转换常用的annotation有:

  1. @XmlType
  2. @XmlElement
  3. @XmlRootElement
  4. @XmlAttribute
  5. @XmlAccessorType
  6. @XmlAccessorOrder
  7. @XmlTransient
  8. @XmlJavaTypeAdapter

二.常用annotation使用说明

1.XmlType

  @XmlType用在class类的注解,常与@XmlRootElement,@XmlAccessorType一起使用。它有三个属性:name、propOrder、namespace,经常使用的只有前两个属性。如:

@XmlType(name = "basicStruct", propOrder = {
"intValue",
"stringArray",
"stringValue"
)
在使用@XmlType的propOrder 属性时,必须列出JavaBean对象中的所有属性,否则会报错。

2.@XmlElement

  @XmlElement将java对象的属性映射为xml的节点,在使用@XmlElement时,可通过name属性改变java对象属性在xml中显示的名称。如:

@XmlElement(name="Address")  
private String yourAddress;

3.@XmlRootElement

  @XmlRootElement用于类级别的注解,对应xml的跟元素,常与 @XmlType 和 @XmlAccessorType一起使用。如:

@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Address {}

4.@XmlAttribute

  @XmlAttribute用于把java对象的属性映射为xml的属性,并可通过name属性为生成的xml属性指定别名。如:
@XmlAttribute(name="Country")
private String state;

5.@XmlAccessorType

  @XmlAccessorType用于指定由java对象生成xml文件时对java对象属性的访问方式。常与@XmlRootElement、@XmlType一起使用。它的属性值是XmlAccessType的4个枚举值,分   别为:

  XmlAccessType.FIELD:java对象中的所有成员变量

  XmlAccessType.PROPERTY:java对象中所有通过getter/setter方式访问的成员变量

  XmlAccessType.PUBLIC_MEMBER:java对象中所有的public访问权限的成员变量和通过getter/setter方式访问的成员变量

  XmlAccessType.NONE:java对象的所有属性都不映射为xml的元素

  注意:@XmlAccessorType的默认访问级别是XmlAccessType.PUBLIC_MEMBER,因此,如果java对象中的private成员变量设置了public权限的getter/setter方法,就不要在private变量上使用@XmlElement和@XmlAttribute注解,否则在由java对象生成xml时会报同一个属性在java类里存在两次的错误。同理,如果@XmlAccessorType的访问权限为XmlAccessType.NONE,如果在java的成员变量上使用了@XmlElement或@XmlAttribute注解,这些成员变量依然可以映射到xml文件。

6.@XmlAccessorOrder

  @XmlAccessorOrder用于对java对象生成的xml元素进行排序。它有两个属性值:

  AccessorOrder.ALPHABETICAL:对生成的xml元素按字母书序排序

  XmlAccessOrder.UNDEFINED:不排序

7.@XmlTransient

  @XmlTransient用于标示在由java对象映射xml时,忽略此属性。即,在生成的xml文件中不出现此元素。

8.@XmlJavaTypeAdapter

  @XmlJavaTypeAdapter常用在转换比较复杂的对象时,如map类型或者格式化日期等。使用此注解时,需要自己写一个adapter类继承XmlAdapter抽象类,并实现里面的方法。

  @XmlJavaTypeAdapter(value=xxx.class),value为自己定义的adapter类

  XmlAdapter如下:

public abstract class XmlAdapter<ValueType,BoundType> {
// Do-nothing constructor for the derived classes.
protected XmlAdapter() {}
// Convert a value type to a bound type.
public abstract BoundType unmarshal(ValueType v);
// Convert a bound type to a value type.
public abstract ValueType marshal(BoundType v);
}

三.示例

  1.Shop.java

 import java.util.Set;

 import javax.xml.bind.annotation.XmlAccessOrder;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlAccessorOrder; @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name ="shop", propOrder = {"name", "number","describer", "address","orders"})
@XmlRootElement(name ="CHMart")
public class Shop { @XmlAttribute
privateString name; // @XmlElement
privateString number; @XmlElement
privateString describer; @XmlElementWrapper(name ="orders")
@XmlElement(name ="order")
privateSet<Order> orders; @XmlElement
privateAddress address; publicShop() {
} publicShop(String name, String number, String describer, Address address) {
this.name = name;
this.number = number;
this.describer = describer;
this.address = address;
} getter/setter略
}

备注:同时使用了@XmlType(propOrder={})和 @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL),但是生成的xml只按照propOrder定义的顺序生成元

  2.Order.java

 import java.math.BigDecimal;
import java.util.Date; import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; @XmlType(name="order",propOrder={"shopName","orderNumber","price","amount","purDate","customer"})
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Order { // @XmlElement  
privateString shopName; @XmlAttribute
privateString orderNumber; // @XmlElement
@XmlJavaTypeAdapter(value=DateAdapter.class)
privateDate purDate; // @XmlElement
privateBigDecimal price; // @XmlElement
privateint amount; // @XmlElement
privateCustomer customer; publicOrder() {
} publicOrder(String shopName, String orderNumber, Date purDate,
BigDecimal price,int amount) {
this.shopName = shopName;
this.orderNumber = orderNumber;
this.purDate = purDate;
this.price = price;
this.amount = amount;
} getter/setter略
}

备注:@XmlAccessorType(XmlAccessType.FIELD),所以此处注释掉了@XmlElement,xml中依然会生成这些元素

  3.Customer.java

 import java.util.Set;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType; @XmlType
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Customer { @XmlAttribute
privateString name; privateString gender; privateString phoneNo; privateAddress address; privateSet<Order> orders; publicCustomer() {
} publicCustomer(String name, String gender, String phoneNo, Address address) {
this.name = name;
this.gender = gender;
this.phoneNo = phoneNo;
this.address = address;
} getter/setter略
}

  4.Address.java

 import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessOrder;
import javax.xml.bind.annotation.XmlAccessorOrder; @XmlType(propOrder={"state","province","city","street","zip"})
@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement
public class Address { @XmlAttribute 
privateString state; @XmlElement
privateString province; @XmlElement
privateString city; @XmlElement
privateString street; @XmlElement
privateString zip; publicAddress() {
super();
} publicAddress(String state, String province, String city, String street,
String zip) {
super();
this.state = state;
this.province = province;
this.city = city;
this.street = street;
this.zip = zip;
} getter/setter略
}

备注:虽然@XmlAccessorType为XmlAccessType.NONE,但是在java类的私有属性上加了@XmlAttribute和@XmlElement注解后,这些私有成员会映射生成xml的元素

  5.DateAdapter.java

 import java.util.Date;
import java.text.SimpleDateFormat; import javax.xml.bind.annotation.adapters.XmlAdapter; public class DateAdapter extendsXmlAdapter<String, Date> { private String pattern = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat fmt =new SimpleDateFormat(pattern); @Override
publicDate unmarshal(String dateStr) throwsException {
return fmt.parse(dateStr);
} @Override
publicString marshal(Date date) throwsException {
return fmt.format(date);
} }

备注:用于格式化日期在xml中的显示格式,并且由xml unmarshal为java对象时,将字符串解析为Date对象

  6.ShopTest.java

 import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.Set; import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller; public class ShopTest { publicstatic void main(String[] args) throws JAXBException, IOException{
Set<Order> orders =new HashSet<Order>(); Address address1 =new Address("China","ShangHai", "ShangHai", "Huang","");
Customer customer1 =new Customer("Jim","male", "", address1);
Order order1 =new Order("Mart","LH59900", new Date(), newBigDecimal(),);
order1.setCustomer(customer1); Address address2 =new Address("China","JiangSu", "NanJing", "ZhongYangLu","");
Customer customer2 =new Customer("David","male", "", address2);
Order order2 =new Order("Mart","LH59800", new Date(), newBigDecimal(),);
order2.setCustomer(customer2); orders.add(order1);
orders.add(order2); Address address3 =new Address("China","ZheJiang", "HangZhou", "XiHuRoad","");
Shop shop =new Shop("CHMart","", "EveryThing",address3);
shop.setOrder(orders); FileWriter writer =null;
JAXBContext context = JAXBContext.newInstance(Shop.class);
try{
Marshaller marshal = context.createMarshaller();
marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
marshal.marshal(shop, System.out); writer =new FileWriter("shop.xml");
marshal.marshal(shop, writer);
}catch (Exception e) {
e.printStackTrace();
} Unmarshaller unmarshal = context.createUnmarshaller();
FileReader reader =new FileReader("shop.xml") ;
Shop shop1 = (Shop)unmarshal.unmarshal(reader); Set<Order> orders1 = shop1.getOrder();
for(Order order : orders1){
System.out.println("***************************");
System.out.println(order.getOrderNumber());
System.out.println(order.getCustomer().getName());
System.out.println("***************************");
}
}
}

  7.生成的xml文件

 <?xml version="1.0"encoding="UTF-8"standalone="yes"?>
<CHMart name="CHMart">
<number></number>
<describer>EveryThing</describer>
<address state="China">
<province>ZheJiang</province>
<city>HangZhou</city>
<street>XiHuRoad</street>
<zip></zip>
</address>
<orders>
<order orderNumber="LH59800">
<shopName>Mart</shopName>
<price></price>
<amount></amount>
<purDate>--::</purDate>
<customer name="David">
<gender>male</gender>
<phoneNo></phoneNo>
<address state="China">
<province>JiangSu</province>
<city>NanJing</city>
<street>ZhongYangLu</street>
<zip></zip>
</address>
</customer>
</order>
<order orderNumber="LH59900">
<shopName>Mart</shopName>
<price></price>
<amount></amount>
<purDate>--::</purDate>
<customer name="Jim">
<gender>male</gender>
<phoneNo></phoneNo>
<address state="China">
<province>ShangHai</province>
<city>ShangHai</city>
<street>Huang</street>
<zip></zip>
</address>
</customer>
</order>
</orders>
</CHMart>

以上是以一个简单的商店订单模型作为示例。

转自:http://blog.csdn.net/czplplp_900725/article/details/7888896

JAXB注解使用[转]的更多相关文章

  1. JAXB注解的使用详解

    前言: 最近一直在做各种接口的对接,接触最多的数据类型就是JSON和XML数据,还有XML中包含JSON的数据,而在Java中对象和XML之间的转换经常用到JAXB注解,抽空在这里总结一下,首先做一下 ...

  2. JAXB注解【转】

    http://blog.csdn.net/lw371496536/article/details/6942045 JAXB(Java API for XML Binding),提供了一个快速便捷的方式 ...

  3. JAXB 注解

    JAXB(Java API for XML Binding),它提供了一个便捷的方式高速Java对象XML转变.于JAX-WS(Java的WebService规范之中的一个)中,JDK1.6 自带的版 ...

  4. xml和java对象互转:JAXB注解的使用详解

    先看工具类: import org.slf4j.Logger; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; ...

  5. JAXB注解 @XmlRootElement 及XML文件解析详解

    @Retention(value=RUNTIME) @Target(value=TYPE) public @interface XmlRootElement @Inherited @Retention ...

  6. JAXB注解使用

    一.Jaxb处理java对象和xml之间转换常用的annotation有: @XmlType @XmlElement @XmlRootElement @XmlAttribute @XmlAccesso ...

  7. JAXB常用注解讲解(超详细)

    简介: JAXB(Java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术.该过程中,JAXB也提供了将XML实例 ...

  8. JAX-WS:背后的技术JAXB及传递Map

    转载:http://www.programgo.com/article/98912703200/ 1.什么是JAX-WS JAX-WS (JavaTM API for XML-Based Web Se ...

  9. 当Jaxb遇到泛型

    前言: 最近的工作内容跟银行有些交互, 对方提供的数据格式采用xml(不是预期的json/protobuf). 为了开发方便, 需要借助jaxb来实现xml和java对象之间的映射. 它还是有点像ja ...

随机推荐

  1. 第七章 常用Java集合类总结

    7.1.List(允许重复元素) ArrayList: 底层数据结构:Object[] 在查询(get).遍历(iterator).修改(set)使用的比较多的情况下,用ArrayList 可扩容,容 ...

  2. .Net应用程序打包部署总结

    编译源代码并完成测试以后,开发过程其实并没有结束.在这个极端,需要把应用程序提供给用户.无论是ASP.NET应用程序,客户端应用程序还是 Compact Framework构建的应用程序,开发出来的软 ...

  3. Squid普通代理&&透明代理&&反向代理学习

    普通代理                                                              背景                                 ...

  4. [React GraphQL] Pass Parameters to urql's useQuery React Hook

    Showing how to use 'uqrl' library to do GraphQL in React. import React, {useState} from 'react' impo ...

  5. Java从零开始学三十八(JAVA IO- 重定向IO)

    一.三个静态变量 java.lang.System提供了三个静态变量 System.in(默认键盘) System.out(默认显示器) System.err 二.重写向方法 System提供了三个重 ...

  6. python中的静态成员方法和类成员方法

    Python的静态方法和类成员方法都可以被类或实例访问,两者概念不容易理清,但还是有区别的: 1)静态方法无需传入self参数,类成员方法需传入代表本类的cls参数: 2)从第1条,静态方法是无法访问 ...

  7. LogUtils.java

    package com.xdsjs.save.utils; /** * 日志相关管理类 * Created by xdsjs on 2015/10/13. */ import android.util ...

  8. 在Tomcat下指定Jsp生成的Java文件路径

    在tomcat的配置文件server.xml(路径:tomcat路径\conf下面)里,找到:<Context docBase="D:/workspace/icinfo/trunk/w ...

  9. Divisibility by Eight

    把当前数删除几位然后能够整除与8 那么可得知大于3位数的推断能否整除于八的条件是(n%1000)%8==0 能够得出我们的结论:仅仅须要枚举后三位后两位后一位就可以知道是否可整除于8 #include ...

  10. exception PLS-00403: expression 'V_END' cannot be used as an INTO-target of a SELECT/FETCH statement

      exception PLS-00403: expression 'V_END' cannot be used as an INTO-target of a SELECT/FETCH stateme ...