java转xml

使用jackson系列

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
  <version>2.9.5</version>
</dependency>

java类转XML

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
import com.qbsea.mysboot2shirojwt.test.xml.model.RefundRequest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@Test
public void test() throws JsonProcessingException {
	XmlMapper xmlMapper = new XmlMapper();
	xmlMapper.registerModule(new JaxbAnnotationModule());
	xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
	xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

	RefundRequest refundRequest = new RefundRequest();
	refundRequest.setFlowNo("flowNo");
	refundRequest.setRefundTradeNo("refundTradeNo");
	refundRequest.setTotalFee(100);
	refundRequest.setRefundFee(200);
	refundRequest.setRefundReason("refundReason");
	refundRequest.setAppId("appId");
	refundRequest.setMchId("mchId");
	refundRequest.setNonce("nonce");
	refundRequest.setSignature("signature");
	String xmlStr = xmlMapper.writeValueAsString(refundRequest);
	System.out.println(xmlStr);
	System.out.println("------------");
}

 涉及的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;
}
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 {

	//小程序应用ID
	@XmlElement(name = "appid")
	private String appId;

	//商户ID
	@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";
}

猜你喜欢

转载自blog.csdn.net/maqingbin8888/article/details/83510375
今日推荐