文档章节

JAXB XML与对象之间转换

李星
 李星
发布于 2014/08/28 18:54
字数 948
阅读 6151
收藏 15


使用jaxb 实现对象与xml之间的转换,并且是 soap报文与对象转换

1.测试用例

public class TestJaxb {
    @Test
    public void testToObject(){
         JaxbBinder jaxbBinder = new JaxbBinder(SoapEnvelope.class);


       URL url = this.getClass().getClassLoader().getResource("receB2COrderResponse.xml");
        String xml = null;
        try {
            xml = FileUtils.readFileToString(new File(url.getPath())) ;
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        SoapEnvelope envelope =jaxbBinder.fromXml(xml);

        Assert.notNull(envelope,"envelope数据为空");
        Assert.notNull(envelope.getBody(),"body数据为空");
        Assert.notNull(envelope.getBody().getReceB2COrderResponseList(),"body.list数据为空");
        Assert.notNull(envelope.getBody().getReceB2COrderResponseList().get(0),"body.list[0]数据为空");
        Assert.notNull(envelope.getBody().getReceB2COrderResponseList().get(0).getOrderNo(),"body.list[0]数据为空");
        System.out.println("getOrderNo="+envelope.getBody().getReceB2COrderResponseList().get(0).getOrderNo());

        System.out.println("\ndata="+ (envelope).toString());


    }
    @Test
    public void testToXml(){
        ReceB2COrderRequest re = new ReceB2COrderRequest();
        re.setBuyerContact("test111123123");
        re.setBuyerId("asdfsadfasdf");
        re.setBuyerName("aaaaaaaaaaa");
        SoapBody body = new SoapBody();
        body.setReceB2COrderRequestList(Arrays.asList(re));

        SoapEnvelope envelope = new SoapEnvelope(null,body);

        JaxbBinder jaxbBinder = new JaxbBinder(SoapEnvelope.class);

        String xml =jaxbBinder.toXml(envelope,"utf-8");


        System.out.println("\nxml="+ xml);


    }
2.转换工具
import javax.xml.bind.*;
import javax.xml.namespace.QName;
import java.io.File;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
/**
 * 使用Jaxb2.0实现XML<->Java Object的Binder.
 * 特别支持Root对象是List的情形.
 */
public class JaxbBinder {
	//多线程安全的Context.
	private JAXBContext jaxbContext;

	/**
	 * @param types 所有需要序列化的Root对象的类型.
	 */
	public JaxbBinder(Class<?>... types) {
		try {
			jaxbContext = JAXBContext.newInstance(types);
		} catch (JAXBException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Java Object->Xml.
	 */
	public String toXml(Object root, String encoding) {
		try {
			StringWriter writer = new StringWriter();
			createMarshaller(encoding).marshal(root, writer);
			return writer.toString();
		} catch (JAXBException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Java Object->Xml, 特别支持对Root Element是Collection的情形.
	 */
	@SuppressWarnings("unchecked")
	public String toXml(Collection root, String rootName, String encoding) {
		try {
			CollectionWrapper wrapper = new CollectionWrapper();
			wrapper.collection = root;

			JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(new QName(rootName),
					CollectionWrapper.class, wrapper);

			StringWriter writer = new StringWriter();
			createMarshaller(encoding).marshal(wrapperElement, writer);

			return writer.toString();
		} catch (JAXBException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Xml->Java Object.
	 */
	@SuppressWarnings("unchecked")
	public <T> T fromXml(String xml) {
		try {
			StringReader reader = new StringReader(xml);
			return (T) createUnmarshaller().unmarshal(reader);
		} catch (JAXBException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 创建Marshaller, 设定encoding(可为Null).
	 */
	public Marshaller createMarshaller(String encoding) {
		try {
			Marshaller marshaller = jaxbContext.createMarshaller();

			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

			if (StringUtils.isNotBlank(encoding)) {
				marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
			}
			return marshaller;
		} catch (JAXBException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 创建UnMarshaller.
	 */
	public Unmarshaller createUnmarshaller() {
		try {
			return jaxbContext.createUnmarshaller();
		} catch (JAXBException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 封装Root Element 是 Collection的情况.
	 */
	public static class CollectionWrapper {
		@SuppressWarnings("unchecked")
		@XmlAnyElement
		protected Collection collection;
	}


    @SuppressWarnings("unchecked")
    public <T> T fromXML(String fileName) {
        return (T)fromXML(new File(fileName));
    }


    @SuppressWarnings("unchecked")
    public <T> T fromXML(File file) {
        try {
            Unmarshaller unmarshaller = createUnmarshaller();
            return (T) unmarshaller.unmarshal(file);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }


    @SuppressWarnings("unchecked")
    public <T> T fromXML(InputStream stream) {
        try {
            Unmarshaller unmarshaller = createUnmarshaller();
            return (T) unmarshaller.unmarshal(stream);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }



3.XML报文实例(receB2COrderResponse.xml)

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
    <ns1:receiveB2COrderResponse xmlns:ns1="http://www.sdo.com/mas/api/receive/">
        <return>
            <customerName>爱奇艺</customerName>
            <customerNo>332396</customerNo>
            <orderAmount>30.00</orderAmount>
            <orderNo>2014081809451210442</orderNo>
            <orderType>OT001</orderType>
            <returnInfo/>
            <sessionId>72041119-5d40-42dc-afec-980cbf0122a4</sessionId>
            <signature/>
            <tokenId>4A8A8F14C3BED9151F51C0096319A664AAFD91E5B2982EAB21DDE8C557FC5A52B887E8CBF9AE3B19</tokenId>
            <transNo>C20140818094536462081</transNo>
            <transStatus>00</transStatus>
            <transTime>20140818094518</transTime>
        </return>
    </ns1:receiveB2COrderResponse>
</soap:Body>
</soap:Envelope>
4.testToXml()输出的报文内容:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                  xmlns:rec="http://www.sdo.com/mas/api/receive/">
    <soapenv:Header>
    </soapenv:Header>
    <soapenv:Body>
        <rec:receiveB2COrder>
            <arg0>
                <buyerContact></buyerContact>
                <buyerId></buyerId>
                <buyerIp></buyerIp>
                <buyerName></buyerName>
                <cardPayInfo></cardPayInfo>
                <cardValue></cardValue>
                <currency>CNY</currency>
                <depositId></depositId>
                <depositIdType></depositIdType>
                <expireTime></expireTime>
                <instCode></instCode>
                <language>zh-CN</language>
                <notifyUrl>sntCode=sdocard</notifyUrl>
                <orderAmount>1.00</orderAmount>
                <orderNo>2014081319114151822</orderNo>
                <orderTime>20140813191141</orderTime>
                <pageUrl>fdction?paymentCode=sdocard</pageUrl>
                <payChannel></payChannel>
                <payType></payType>
                <payeeId></payeeId>
                <payerAuthTicket></payerAuthTicket>
                <payerId></payerId>
                <payerMobileNo></payerMobileNo>
                <productDesc></productDesc>
                <productId></productId>
                <productName></productName>
                <productNum></productNum>
                <productUrl></productUrl>
                <sellerId></sellerId>
                <terminalType></terminalType>
                <unitPrice></unitPrice>
            </arg0>
        </rec:receiveB2COrder>
    </soapenv:Body>
</soapenv:Envelope>




5.java的对象(省略了getter/setter)

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlRootElement(name = "Envelope", namespace = NAMESPACE_OF_ENVELOPE)
    public class SoapEnvelope {
            /**
     * soap 中 envelope namespace
     */
        public static final String NAMESPACE_OF_ENVELOPE = "http://schemas.xmlsoap.org/soap/envelope/";
    /**
     * soap 中 receiveB2COrderResponse namespace
     */
        public static final String NAMESPACE_OF_RECEIVEB2CORDER = "http://www.sdo.com/mas/api/receive/";


        @XmlElement(name = "Header", namespace = NAMESPACE_OF_ENVELOPE)
        private SoapHeader header;
        @XmlElement(name = "Body", namespace = NAMESPACE_OF_ENVELOPE )
        private SoapBody body;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    public class SoapBody {
            /**
     * soap 中 envelope namespace
     */
        public static final String NAMESPACE_OF_ENVELOPE = "http://schemas.xmlsoap.org/soap/envelope/";
    /**
     * soap 中 receiveB2COrderResponse namespace
     */
        public static final String NAMESPACE_OF_RECEIVEB2CORDER = "http://www.sdo.com/mas/api/receive/";
        
        @XmlElement(name = "Fault", namespace = NAMESPACE_OF_ENVELOPE)
        private Fault fault;

        @XmlElementWrapper(name = "receiveB2COrder", namespace = NAMESPACE_OF_RECEIVEB2CORDER)
        @XmlElement(name = "arg0")
        private List<ReceB2COrderRequest> receB2COrderRequestList;
        @XmlElementWrapper(name = "receiveB2COrderResponse", namespace = NAMESPACE_OF_RECEIVEB2CORDER)
        @XmlElement(name = "return")
        private List<ReceB2COrderResponse> receB2COrderResponseList;

    }
    @XmlAccessorType(XmlAccessType.FIELD)
    public class ReceB2COrderRequest {
        private String orderNo;
        private String orderAmount;
        private String orderTime;
        private String expireTime;
        private String currency;
        private String payType;
        private String payChannel;
        private String instCode;
        private String cardValue;
        private String language;
        private String pageUrl;
        private String notifyUrl;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    public class ReceB2COrderResponse{
        private String orderNo;
        private String transNo;
        private String customerName;
        private String customerNo;
        private String customerLogoUrl;
        private String orderType;
        private String orderAmount;
        private String transStatus;
        private String transTime;
        private String tokenId;
        private String sessionId;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    public static class SoapHeader {
    }







© 著作权归作者所有

李星

李星

粉丝 15
博文 20
码字总数 9685
作品 0
长宁
程序员
私信 提问
jaxb替换smooks项目方案建议书

1 前言 本文档是描述Smooks的应用情况,以及使用Jaxb替换smooks的可行性分析及实施方案,有不足之处还望谅解和指出。 2 背景 项目系统中使用Smooks出现几次死锁问题导致系统宕机,其后针对S...

WinnieChan
2013/08/02
0
0
SpringMVC 中整合JSON、XML视图一

SpringMVC中整合了JSON、XML的视图,可以通过这些视图完成Java对象到XML、JSON的转换。转换XML提供了MarshallingView,开发者只需用注入相应的marshaller、和属性配置,即可自动完成Java的M...

ibm_hoojo
2011/04/29
0
0
JaxbContext生成xml文件或java类对象转化注解

JAXB(Java API for XML Binding),提供了一个快速便捷的方式将Java对象与XML进行转换。在JAX-WS(Java的WebService规范之一)中,JDK1.6 自带的版本JAX-WS2.1,其底层支持就是JAXB。 JAXB...

K_ONE
2016/02/16
112
0
使用jaxb 实现对象与xml之间的转换,并且是 soap报文与对象转换

使用jaxb 实现对象与xml之间的转换,并且是 soap报文与对象转换 1.测试用例 public class TestJaxb { 2.转换工具 import javax.xml.bind.*;import javax.xml.namespace.QName;import java.io....

xiaomin0322
2018/12/04
0
0
JAXB 应用指南

文章转自:http://blog.csdn.net/darxin/article/details/4845820 JAXB(Java Architecture for XML Binding)是一种特殊的序列化/反序列化工具。它可以使XML数据以Java Objects的形式直接应...

红薯
2011/08/06
4.7K
0

没有更多内容

加载失败,请刷新页面

加载更多

jenkins定时构建时间设置

举几个例子: 每隔5分钟构建一次 H/5 * * * * 每两小时构建一次 H H/2 * * * 每天中午12点定时构建一次 H 12 * * * 每天下午18点定时构建一次 H 18 * * * 在每个小时的前半个小时内的每10分钟...

shzwork
24分钟前
0
0
Myeclipse 问题记录

1. 创建maven聚合(pom) 工程 ,子项目会带上 maven app这些文字,删掉后会导致工程文件在working set里消失,解决办法:右键子项目 import as project 解决问题。...

无敌小学僧
51分钟前
1
0
《Chez Scheme初探》定义变量、递归、测试性能、并列代码编写

普通fib函数 (define (fact n) (if (= n 1) 1 (* n (fact (- n 1)) ) )) 尾递归fib函数 (define (fact-tail n) (fact-rec n n))(defi......

flash胜龙
51分钟前
1
0
任正非对华为热点问题的回应亮了,终于知道华为为什么能扛过这一次的冲击!

任正非对华为热点问题的回应亮了,终于知道华为为什么能扛过这一次的冲击! 如果你是华为的老板,看到一条传遍网络的“美国封锁华为”、“华为禁令”的消息,你会怎么办? 昨天上午,华为创始...

forespider
今天
2
0
Java HTTP 组件库选型看这篇就够了

最近项目需要使用 Java 重度调用 HTTP API 接口,于是想着封装一个团队公用的 HTTP client lib. 这个库需要支持以下特性: 连接池管理,包括连接创建和超时、空闲连接数控制、每个 host 的连...

Java面经
今天
5
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部