jaxb-xml和javabean转换实战

来源:互联网 发布:seo自学 编辑:程序博客网 时间:2024/04/30 01:34
/** * 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;@XmlAttributepublic String getPlatformNo() {return platformNo;}public void setPlatformNo(String platformNo) {this.platformNo = platformNo;}@XmlElementpublic int getPlatformUserNo() {return platformUserNo;}public void setPlatformUserNo(int platformUserNo) {this.platformUserNo = platformUserNo;}@XmlElementpublic 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;}@XmlElementpublic String getCallbackUrl() {return callbackUrl;}public void setCallbackUrl(String callbackUrl) {this.callbackUrl = callbackUrl;}@XmlElementpublic 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);e.printStackTrace();throw new RuntimeException(e.getMessage(), e);}}


0 0