上篇写了 object convert xml 觉着还差点,仔细想想忘了贴上xml转对象的了,此处是当参数以xml给某系统后对返回的xml结果转换;
//设置XStream编码格式
private static XStream xstream = new XStream(new DomDriver("GBK"));
/*
* xml响应模板 <root> <head> ... </head> </root>
*/
/**
* xml转object
* @param responseXml xml请求模板
* @param alias 返回根标签别名
* @param clazzResponse 响应类
* @return
*/
@SuppressWarnings("unchecked")
public static <T extends Response<InteractionResponse>, R> R toObject(String responseXml, String alias,
Class<T> clazzResponse) {
xstream.alias(alias, clazzResponse);
T response = (T) xstream.fromXML(responseXml);
return (R) response.getHead();
}
@JsonInclude(Include.NON_NULL)
public class InteractionResponse implements Serializable {
private int code;
private String message;
//getter setter ignore
}
public class Response<R extends InteractionResponse> implements Serializable {
R head;
//getter setter ignore
}
注意:标签head就相当于InteractionResponse类,其类的属性名是为head内标签<code>//<message>
测试使用:
/**
*<root>
<head>
<code>1</code>
<message>数据保存成功<message>
</head>
</root>
*
*/
public static void main(String[] args) {
String testXml = "<root>\n" + " <head>\n" + "<code>1</code>\n" + "<message>数据保存成功</message>\n" + "</head>\n"
+ "</root>";
InteractionResponse response = toObject(testXml, "root", Response.class);
System.err.println(response);
}
测试结果:
InteractionResponse [code=1, message=数据保存成功]