jaxb-xml和javabean转换实战

前端之家收集整理的这篇文章主要介绍了jaxb-xml和javabean转换实战前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
/**
 * req 请求参数 XML 格式请求串 sign 签名
 * 
 * @author zsj
 * 
 */
@XmlRootElement(name = "request")
public class Request implements Serializable {
	private static final long serialVersionUID = -7910857770369937355L;
	/**
	 * 请求参数,XML 格式请求串
	 */
	private String req;
	/**
	 * 签名
	 */
	private String sign;
	/**
	 * 商户编号 商户唯一标识
	 */

	private String platformNo;

	/**
	 * 商户平台会员标识-的会员标识
	 */
	private int platformUserNo;
	/**
	 * 请求流水号
	 */
	private String requestNo;
	/**
	 * 页面回跳
	 */
	private String callbackUrl;
	/**
	 * 服务器通知
	 */
	private String notifyUrl;
	/**
	 * 向yeepay发起求情的action
	 */
	private String yeePayAction;

	@XmlAttribute
	public String getPlatformNo() {
		return platformNo;
	}

	public void setPlatformNo(String platformNo) {
		this.platformNo = platformNo;
	}

	@XmlElement
	public int getPlatformUserNo() {
		return platformUserNo;
	}

	public void setPlatformUserNo(int platformUserNo) {
		this.platformUserNo = platformUserNo;
	}

	@XmlElement
	public String getRequestNo() {
		return requestNo;
	}

	public void setRequestNo(String requestNo) {
		this.requestNo = requestNo;
	}

	public String getReq() {
		return req;
	}

	public void setReq(String req) {
		this.req = req;
	}

	public String getSign() {
		return sign;
	}

	public void setSign(String sign) {
		this.sign = sign;
	}

	@XmlElement
	public String getCallbackUrl() {
		return callbackUrl;
	}

	public void setCallbackUrl(String callbackUrl) {
		this.callbackUrl = callbackUrl;
	}

	@XmlElement
	public String getNotifyUrl() {
		return notifyUrl;
	}

	public void setNotifyUrl(String notifyUrl) {
		this.notifyUrl = notifyUrl;
	}

	public String getYeePayAction() {
		return yeePayAction;
	}

	public void setYeePayAction(String yeePayAction) {
		this.yeePayAction = yeePayAction;
	}

}


xml和java对象转换器如下:

	public <T> T toObject(String respXml,Class<T> c) {
		try {
			JAXBContext context = JAXBContext.newInstance(c);
			javax.xml.bind.Unmarshaller unmarshaller = context
					.createUnmarshaller();
			StringReader reader = new StringReader(respXml);
			return (T) unmarshaller.unmarshal(new StreamSource(reader));
		} catch (Exception e) {
			LOG.error(e.getMessage(),e);
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(),e);
		}
	}

	public String toXml(Object req,Class<?> c) {
		try {
			StringWriter writer = new StringWriter();
			JAXBContext context = JAXBContext.newInstance(c);
			javax.xml.bind.Marshaller marshaller = context.createMarshaller();
			marshaller.marshal(req,new StreamResult(writer));
			return writer.toString();
		} catch (Exception e) {
			LOG.error(e.getMessage(),e);
		}
	}

猜你在找的XML相关文章