SpringBoot接收Xml格式参数并转换为POJO对象
1. 所需JavaBean
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {"head","body" })
@XmlRootElement(name = "xml")
@Data
public class XmlRemoteDto {
private Head head;
private Body body;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "body")
@XmlType(name = "userInfo")
@Data
public class Body {
@XmlElement(name = "userInfo")
private UserInfo userInfo;
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "head")
@Data
public class Head {
@XmlElement(name = "token")
private String token;
}
@Data
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "userInfo")
public class UserInfo {
@XmlElement(name = "name")
private String name;
@XmlElement(name = "password")
private String password;
@XmlElement(name = "email")
private String email;
}
2. XML解析工具类
@Slf4j
public class XmlParseUtil {
public static Object convertXmlStrToObject(Class clazz, String xml) {
Object xmlObject = null;
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
StringReader sr = new StringReader(xml);
xmlObject = unmarshaller.unmarshal(sr);
} catch (Exception e) {
log.error("convert xmlStr to object error, msg <{}>",e.getMessage(),e);
}
return xmlObject;
}
}
3. 处理接口
@PostMapping("/convertXmlToObject")
public String fzpAgencyInfo(@RequestBody String paramXml) {
XmlRemoteDto xmlRemoteDto = (XmlRemoteDto) XmlParseUtil.convertXmlStrToObject(XmlRemoteDto.class, paramXml);
Body body = xmlRemoteDto.getBody();
UserInfo userInfo = body.getUserInfo();
return userInfo.toString();
}
4. 测试
<xml>
<head>
<token>1234</token>
</head>
<body>
<userInfo>
<name>admin</name>
<password>123456</password>
<email>123@qq.com</email>
</userInfo>
</body>
</xml>
|