JAXB教程

简介

JAXB(Java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术。该过程中,JAXB也提供了将XML实例文档反向生成Java对象树的方法,并能将Java对象树的内容重新写到 XML实例文档。
JAXB2.0是JDK 1.6的组成部分。我们不需要下载第三方jar包 即可做到轻松转换。

概念

Marshaller接口,将Java对象序列化为XML数据。
Unmarshaller接口,将XML数据反序列化为Java对象。

@XmlType,将Java类或枚举类型映射到XML模式类型
@XmlAccessorType(XmlAccessType.FIELD) ,控制字段或属性的序列化。FIELD表示JAXB将自动绑定Java类中的每个非静态的(static)、非瞬态的(由@XmlTransient标 注)字段到XML。其他值还有XmlAccessType.PROPERTY和XmlAccessType.NONE。
@XmlAccessorOrder,控制JAXB 绑定类中属性和字段的排序。
@XmlJavaTypeAdapter,使用定制的适配器(即扩展抽象类XmlAdapter并覆盖marshal()和unmarshal()方法),以序列化Java类为XML。
@XmlElementWrapper ,对于数组或集合(即包含多个元素的成员变量),生成一个包装该数组或集合的XML元素(称为包装器)。
@XmlRootElement,将Java类或枚举类型映射到XML元素。
@XmlElement,将Java类的一个属性映射到与属性同名的一个XML元素。
@XmlAttribute,将Java类的一个属性映射到与属性同名的一个XML属性。

示例

Order.java

package com.ricky.domain;

import javax.xml.bind.annotation.*;
import java.util.List;
import java.util.Set;

/**
 * 订单
 *
 * @author Ricky Fung
 * @create 2016-06-13 18:27
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
@XmlType(propOrder = {"id","totalPrice","category","shoppingList","tags","address"})
public class Order {

    @XmlAttribute(name="id")
    private long id;
    private String category;

    @XmlElementWrapper(name = "shopping_list")
    @XmlElement(name = "shopping_item")
    private List<ShoppingItem> shoppingList;

    @XmlElementWrapper(name = "tags")
    @XmlElement(name = "tag")
    private Set<String> tags;

    @XmlElement(name = "addr", required = true)
    private Address address;

    @XmlElement(name = "total_price")
    private float totalPrice;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public List<ShoppingItem> getShoppingList() {
        return shoppingList;
    }

    public void setShoppingList(List<ShoppingItem> shoppingList) {
        this.shoppingList = shoppingList;
    }

    public Set<String> getTags() {
        return tags;
    }

    public void setTags(Set<String> tags) {
        this.tags = tags;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public float getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(float totalPrice) {
        this.totalPrice = totalPrice;
    }

    @Override
    public String toString() {
        return "Order{" +
                "id=" + id +
                ", category='" + category + '\'' +
                ", shoppingList=" + shoppingList +
                ", tags=" + tags +
                ", address=" + address +
                ", totalPrice=" + totalPrice +
                '}';
    }
}

ShoppingItem.java

package com.ricky.domain;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

/**
 * 购物项
 *
 * @author Ricky Fung
 * @create 2016-06-13 19:00
 */
@XmlAccessorType(XmlAccessType.FIELD)
public class ShoppingItem {
    private String name;
    private float price;
    private int num;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    @Override
    public String toString() {
        return "ShopItem{" +
                "name='" + name + '\'' +
                ", price=" + price +
                ", num=" + num +
                '}';
    }
}

Address.java

package com.ricky.domain;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;

/**
 * 收货地址
 *
 * @author Ricky Fung
 * @create 2016-06-13 18:28
 */
@XmlAccessorType(XmlAccessType.FIELD)
public class Address {
    private String province;
    private String city;
    private String district;
    private String street;

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getDistrict() {
        return district;
    }

    public void setDistrict(String district) {
        this.district = district;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    @Override
    public String toString() {
        return "Address{" +
                "province='" + province + '\'' +
                ", city='" + city + '\'' +
                ", district='" + district + '\'' +
                ", street='" + street + '\'' +
                '}';
    }
}

JAXBDemo.java

package com.ricky;

import com.ricky.domain.Address;
import com.ricky.domain.Order;
import com.ricky.domain.ShoppingItem;
import com.ricky.util.JAXBUtil;
import javax.xml.bind.JAXBException;
import java.util.*;

/**
 * JAXB示例
 *
 * @author Ricky Fung
 * @create 2016-06-13 18:15
 */
public class JAXBDemo {

    public static void main(String[] args) throws JAXBException {

        Order order = new Order();
        order.setId(2);
        order.setCategory("3C");
        Set<String> tags = new HashSet<String>();
        tags.add("3C");
        tags.add("手机");
        order.setTags(tags);

        List<ShoppingItem> shopping_list = new ArrayList<ShoppingItem>();
        ShoppingItem shoppingItem1 = new ShoppingItem();
        shoppingItem1.setName("Apple 6s Plus 64G");
        shoppingItem1.setPrice(6499f);
        shoppingItem1.setNum(1);
        shopping_list.add(shoppingItem1);

        ShoppingItem shoppingItem2 = new ShoppingItem();
        shoppingItem2.setName("魅蓝Note3 32G");
        shoppingItem2.setPrice(999f);
        shoppingItem2.setNum(1);
        shopping_list.add(shoppingItem2);

        order.setShoppingList(shopping_list);

        order.setTotalPrice(7498f);

        Address address = new Address();
        address.setProvince("湖北省");
        address.setCity("武汉市");
        address.setDistrict("武昌区");
        address.setStreet("复兴路");
        order.setAddress(address);

        String xml = JAXBUtils.marshal(order);
        System.out.println("marshaller order:"+xml);

        Order o = JAXBUtils.unmarshal(xml, Order.class);
        System.out.println("unmarshaller order:"+o);
    }
}

JAXBUtils

package com.bytebeats.netty4.common.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @create 2017-01-08 21:06
 */
public class JAXBUtils {
    public final static String CHARSET_NAME = "UTF-8";

    public static String marshal(Object obj) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, CHARSET_NAME);

        StringWriter writer = new StringWriter();
        try{
            jaxbMarshaller.marshal(obj, writer);
            return writer.toString();
        } finally {
            IoUtils.closeQuietly(writer);
        }
    }

    public static <T> T unmarshal(String xml, Class<T> cls) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(cls);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

        StringReader reader = null;
        try{
            reader = new StringReader(xml);
            return (T) jaxbUnmarshaller.unmarshal(reader);
        } finally {
            IoUtils.closeQuietly(reader);
        }
    }
}

忽略字段

使用@XmlTransient

package com.ricky.domain;

import javax.xml.bind.annotation.*;
import java.util.List;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @create 2016-06-14 18:35
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Student {
    private long id;
    private String name;

    @XmlTransient
    private int age;

    @XmlElementWrapper(name = "hobbies")
    @XmlElement(name = "hobby")
    private List<String> hobbies;

    public long getId() {
        return id;
    }

    public void setId(long 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 List<String> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }
}
package com.ricky;

import com.ricky.domain.Student;
import com.ricky.util.JAXBUtil;
import javax.xml.bind.JAXBException;
import java.util.ArrayList;
import java.util.List;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @create 2016-06-14 18:34
 */
public class JAXBExcludeDemo {

    public static void main(String[] args) throws JAXBException {

        Student student = new Student();
        student.setId(1l);
        student.setName("Ricky");
        student.setAge(27);

        List<String> hobbies = new ArrayList<String>();
        hobbies.add("NBA");
        hobbies.add("电影");
        student.setHobbies(hobbies);

        String xml = JAXBUtils.marshal(student);
        System.out.println(xml);
    }
}

参考资料:
https://java.net/projects/jaxb2-commons/pages/Home

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在Spring Boot中整合JAXB,您可以按照以下步骤进行操作: 1. 添加依赖:在您的项目的pom.xml文件中,添加JAXB依赖项。 ```xml <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> ``` 2. 创建Java类:创建要映射到XML的Java类。使用JAXB注解配置类和字段。 ```java @XmlRootElement public class Person { private String name; private int age; // 省略构造函数、getter和setter方法 } ``` 3. 创建XML转换工具类:创建一个工具类,用于执行XML转换操作。 ```java import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.File; public class JAXBUtils { public static void marshal(Object object, File file) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass()); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(object, file); } public static <T> T unmarshal(Class<T> clazz, File file) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); return clazz.cast(unmarshaller.unmarshal(file)); } } ``` 4. 配置Spring Boot:在您的Spring Boot应用程序的配置类上添加JAXB相关的配置。 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; import org.springframework.oxm.jaxb.Jaxb2Marshaller; @Configuration public class JAXBConfig { @Bean public Jaxb2Marshaller jaxb2Marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setPackagesToScan("com.example.demo"); // 设置要扫描的包路径 return marshaller; } @Bean public HttpMessageConverter<Object> marshallingHttpMessageConverter(Jaxb2Marshaller jaxb2Marshaller) { return new MarshallingHttpMessageConverter(jaxb2Marshaller); } } ``` 5. 使用JAXB:在您的控制器或服务类中使用JAXB进行XML转换操作。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class PersonController { @Autowired private Jaxb2Marshaller jaxb2Marshaller; @GetMapping("/person") public Person getPerson() { Person person = new Person(); person.setName("John"); person.setAge(25); return person; } @GetMapping("/xml") public String getXml() { Person person = getPerson(); StringWriter writer = new StringWriter(); jaxb2Marshaller.marshal(person, new StreamResult(writer)); return writer.toString(); } } ``` 这样,当访问`/person`接口时,将返回一个Person对象的JSON表示。当访问`/xml`接口时,将返回Person对象的XML表示。 这就是在Spring Boot中整合JAXB的基本步骤。您可以根据需要进行扩展和自定义。希望对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值