pom.xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.5</version>
</dependency>
TypeReference与Type
import com.fasterxml.jackson.core.type.TypeReference; //能够定义返回值类型比如
xmlMapper.readValue(xmlStr, new TypeReference<RefundRequest>(){}); //其返回值就为RefundRequest
Type
java.lang.reflect.Type //返回类的具体类型
private final Type type;//别个地方传进来的
return xmlMapper.readValue(responseBody.charStream(),new TypeReference<T>(){
@Override
public Type getType() {
return type;
}
});
有时不指定Type会报转化失败
利用XmlMapper将字符串转化为java
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
@Test
public void test(){
String xmlStr = "<xml><appid>appId</appid><mch_id>mchId</mch_id><nonce_str>nonce</nonce_str><sign>signature</sign" +
"><sign_type>HMAC-SHA256</sign_type><transaction_id>flowNo</transaction_id><out_refund_no>refundTradeNo" +
"</out_refund_no><total_fee>100</total_fee><refund_fee>200</refund_fee><refund_desc>refundReason</refund_desc" +
"></xml>";
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.registerModule(new JaxbAnnotationModule());
xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
RefundRequest readValue=null;
try {
readValue = xmlMapper.readValue(xmlStr, new TypeReference<RefundRequest>(){
});
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("==============="+readValue.getFlowNo());
}
Model类
RefundRequest
package com.qbsea.mysboot2shirojwt.test.xml.model;
import lombok.Getter;
import lombok.Setter;
import javax.xml.bind.annotation.XmlElement;
@Getter
@Setter
public class RefundRequest extends WxPayRequest {
@XmlElement(name = "transaction_id")
private String flowNo;
@XmlElement(name = "out_refund_no")
private String refundTradeNo;
@XmlElement(name = "total_fee")
private int totalFee;
@XmlElement(name = "refund_fee")
private int refundFee;
@XmlElement(name = "refund_desc")
private String refundReason;
}
WxPayRequest
package com.qbsea.mysboot2shirojwt.test.xml.model;
import lombok.Getter;
import lombok.Setter;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
@Getter
@Setter
@XmlRootElement(name = "xml")
public abstract class WxPayRequest implements Serializable {
@XmlElement(name = "appid")
private String appId;
@XmlElement(name = "mch_id")
private String mchId;
@XmlElement(name = "nonce_str")
private String nonce;
@XmlElement(name = "sign")
private String signature;
@XmlElement(name = "sign_type")
private String signType = "HMAC-SHA256";
}