XStream进行xml和bean互转

2019-09-10 17:00:13 浏览数 (2)

加入pom

代码语言:javascript复制
<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.4.3</version>
</dependency>
  1. 最简单的使用方式
代码语言:javascript复制
XStream xStream = new XStream();
//声明XStream注解来源
xStream.processAnnotations(FuiouResponse.class);
//xml 转bean
Object o = xStream.fromXML(xmlStr);
//bean 转xml
xStream.toXML(response)
  1. 需要指明注解
代码语言:javascript复制
/**
 * @author laoliangliang
 * @date 2018/11/6 17:00
 */
@XStreamAlias("ap")
public class FuiouResponse {

    @XStreamAlias("signature")
    private String signature;
    @XStreamAlias("plain")
    private Plain plain;

    public void setSignature(String signature) {
        this.signature = signature;
    }

    public String getSignature() {
        return signature;
    }

    public Plain getPlain() {
        return plain;
    }

    public void setPlain(Plain plain) {
        this.plain = plain;
    }

    public class Plain {
        @XStreamAlias("resp_code")
        private String respCode;

        @XStreamAlias("resp_desc")
        private String respDesc;

        public String getRespCode() {
            return respCode;
        }

        public void setRespCode(String respCode) {
            this.respCode = respCode;
        }

        public String getRespDesc() {
            return respDesc;
        }

        public void setRespDesc(String respDesc) {
            this.respDesc = respDesc;
        }
    }
}

和jpa类似,取个别名

0 人点赞