MangoCool

JAXB的初步学习及简单示例

2015-03-16 17:28:24   作者:MangoCool   来源:MangoCool

JAXB能够使用Jackson对JAXB注解的支持实现(jackson-module-jaxb-annotations),既方便生成XML,也方便生成JSON,这样一来可以更好的标志可以转换为JSON对象的JAVA类。这么好用的东西,岂能不会!赶紧试一试,下面是我学习时的一个简单示例,以记录方便自己今后查阅,或许也能帮到你,共同进步!

依赖:jdk1.7

开发环境:ideaIU-14.1.4

测试环境:win7

建立maven工程JAXBDemo,在pom.xml配置文件添加必要的依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>JAXBDemo</groupId>
    <artifactId>JAXBDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

</project>

User类:

/**
 * Created by MANGOCOOL on 2015/3/16.
 */
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="user")
public class User {

    private String name;
    private String sex;
    private int age;
    private int id;

    public String getName() {
        return name;
    }
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }
    @XmlElement
    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }
    @XmlElement(name="Age")
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }
    // @XmlTransient用于标示在由java对象映射xml时,忽略此属性。即,在生成的xml文件中不出现此元素。
    @XmlAttribute(name="Id")
    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return this.id + " " + this.name + " " + this.sex + " " + this.age;
    }
}

Users类

/**
 * Created by MANGOCOOL on 2015/3/16.
 */
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;

@XmlRootElement
public class Users {

    private List<User> userList = new ArrayList<User>();
    public List<User> getUserList() {
        return userList;
    }

    // 如果想在节点外面包一层xml元素节点,可以用
    // @XmlElementWrapper(name="users")
    // @XmlElements({
    // @XmlElement(name = "user", type = User.class),
    // @XmlElement(name = "xxx", type = Xxx.class)
    // 一个集合可以放置多个xml元素名称和对象类型、在xml中是相互独立的集合元素,无包含关系
    // })
    @XmlElements({@XmlElement(name="user", type=User.class)})
    public void setUserList(List<User> userList) {
        this.userList = userList;
    }
}

Java2Xml类:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

/**
 * Created by MANGOCOOL on 2015/3/16.
 */
public class Java2Xml {

    public void javaToXml() {
        try {
            User userA = new User();
            userA.setName("张三");
            userA.setAge(26);
            userA.setSex("男");
            userA.setId(1);

            User userB = new User();
            userB.setName("李四");
            userB.setAge(19);
            userB.setSex("女");
            userB.setId(2);

            User userC = new User();
            userC.setName("王五");
            userC.setAge(22);
            userC.setSex("男");
            userC.setId(3);

            Users users = new Users();
            List<User> list = users.getUserList();
            list.add(userA);
            list.add(userB);
            list.add(userC);

            bean2Xml(users, "D:\\JAXBDemo\\src\\main\\resources\\users.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void bean2Xml(Object bean, String xmlPath) {
        JAXBContext jaxbContext;
        if (null == bean)
            return;
        try {
            // 将对象转变为xml
            jaxbContext = JAXBContext.newInstance(bean.getClass());
            Marshaller marshaller = jaxbContext.createMarshaller();
            // 输出格式化
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            // 输出打印
//            marshaller.marshal(bean, System.out);
            marshaller.marshal(bean, new FileOutputStream(new File(xmlPath)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        new Java2Xml().javaToXml();
    }
}

Xml2Java类:

import org.apache.commons.lang.StringUtils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * Created by MANGOCOOL on 2015/3/16.
 */
public class Xml2Java {

    public void xmlTojava()
    {
        Users users = (Users)xml2Bean(Users.class, "D:\\JAXBDemo\\src\\main\\resources\\users.xml");
        for(User user: users.getUserList())
        {
            System.out.println(user.toString());
        }
    }

    /**
     * 将生成的xml转换为对象
     * @param zClass 转换为实例的对象类类型
     * @param xmlPath 需要转换的xml路径
     */
    public static Object xml2Bean(Class<?> zClass, String xmlPath)
    {
        Object obj = null;
        JAXBContext jaxbContext = null;
        if (StringUtils.isBlank(xmlPath))
            return obj;
        try {
            jaxbContext = JAXBContext.newInstance(zClass);
            // 切记统一编码UTF-8
            InputStream is = new FileInputStream(new File(xmlPath));
            Unmarshaller umarshaller = jaxbContext.createUnmarshaller();
            obj = (Object) umarshaller.unmarshal(is);
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static void main(String[] args){
        new Xml2Java().xmlTojava();
    }
}

users.xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<users>
    <user Id="1">
        <Age>26</Age>
        <name>张三</name>
        <sex>男</sex>
    </user>
    <user Id="2">
        <Age>19</Age>
        <name>李四</name>
        <sex>女</sex>
    </user>
    <user Id="3">
        <Age>22</Age>
        <name>王五</name>
        <sex>男</sex>
    </user>
</users>

jsr173_api-1.0.jaractivation-1.1.jarjaxb-api-2.0.jarjaxb-impl-2.0.1.jarjaxb-xjc-2.0.1.jar

期间遇到一个异常:

com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 3 counts of IllegalAnnotationExceptions
Class has two properties of the same name "age"
 this problem is related to the following location:
  at public int User.getAge()
  at User
  at public java.util.List Users.Users
  at Users
 this problem is related to the following location:
  at public int User.age
  at User
  at public java.util.List Users.Users
  at Users
Class has two properties of the same name "name"
 this problem is related to the following location:
  at public java.lang.String User.getName()
  at User
  at public java.util.List Users.Users
  at Users
 this problem is related to the following location:
  at public java.lang.String User.name
  at User
  at public java.util.List Users.Users
  at Users
Class has two properties of the same name "sex"
 this problem is related to the following location:
  at public java.lang.String User.getSex()
  at User
  at public java.util.List Users.Users
  at Users
 this problem is related to the following location:
  at public java.lang.String User.sex
  at User
  at public java.util.List Users.Users
  at Users
 at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:66)
 at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:364)
 at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:216)
 at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:76)
 at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:55)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:606)
 at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:248)
 at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:235)
 at javax.xml.bind.ContextFinder.find(ContextFinder.java:432)
 at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:637)
 at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584)
 at Java2XML.javaToXml(Java2XML.java:36)
 at Java2XML.main(Java2XML.java:50)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:606)
 at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

问题所在:
User类属性不能定义成public的,以age属性为例,不然得到age的方式有两种,User.age和user.getAge(),会冲突!直接将User所有属性改成private即可解决问题!

文章参考:
        http://www.mkyong.com/java/jaxb-hello-world-example/
        http://blog.csdn.net/ruzhefeng/article/details/6560449
        http://www.cnblogs.com/fragranting/archive/2012/03/25/xml--jaxb.html

标签: JAXB XML JSON 对象 DOM

分享:

上一篇RESTful框架jersey的初步学习和基于tomcat示例

下一篇java转义字符"\"关于split(),replaceAll()的使用心得

关于我

崇尚极简,热爱技术,喜欢唱歌,热衷旅行,爱好电子产品的一介码农。

座右铭

当你的才华还撑不起你的野心的时候,你就应该静下心来学习,永不止步!

人生之旅历途甚长,所争决不在一年半月,万不可因此着急失望,招精神之萎葸。

Copyright 2015- 芒果酷(mangocool.com) All rights reserved. 湘ICP备14019394号

免责声明:本网站部分文章转载其他媒体,意在为公众提供免费服务。如有信息侵犯了您的权益,可与本网站联系,本网站将尽快予以撤除。