登录
注册
写文章
发现
工具
使用XStream完成XML与对象的互转
_3t3lfz KEKfID
编辑文章
使用XStream完成XML与对象的互转
asfx站长
2021.04.10 17:13:38
阅读
1062
maven依赖 ``` <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.3.1</version> </dependency> ``` XStreamUtil.java ``` import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.mapper.MapperWrapper; /** * @Description XStream 工具类 */ public class XStreamUtil { /** * 将bean转换为xml * @param obj 转换的bean * @return bean转换为xml */ public static String objectToXml(Object obj) { XStream xStream = new XStream(); // XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_"))); // 解决下划线问题(定义别名中的下划线“_”转换为xml后会变成“__”这个符号) //xstream使用注解转换 xStream.processAnnotations(obj.getClass()); xStream.autodetectAnnotations(true); // 开启注解扫描 xStream.aliasSystemAttribute(null, "class"); // 去掉 class 属性 return xStream.toXML(obj); } /** * 将xml转换为bean * @param <T> 泛型 * @param xml 要转换为bean的xml * @param cls bean对应的Class * @return xml转换为bean */ public static <T> T xmlToObject(String xml, Class<T> cls) { // XStream xstream = new XStream(new DomDriver()); XStream xstream = new XStream() { @Override protected MapperWrapper wrapMapper(MapperWrapper next) { return new MapperWrapper(next) { @Override public boolean shouldSerializeMember(Class definedIn, String fieldName) { if (definedIn == Object.class) { return false; } return super.shouldSerializeMember(definedIn, fieldName); } }; } }; //xstream使用注解转换 xstream.processAnnotations(cls); return (T) xstream.fromXML(xml); } } ``` 定义Bean对象,假设为AA.java ``` import com.thoughtworks.xstream.annotations.XStreamAlias; import lombok.Data; /** * AA对象 */ @Data @XStreamAlias("BizContent") public class AA { /** * 城市编码 */ @XStreamAlias("CityCode") private String cityCode; /** * 城市名称 */ @XStreamAlias("CityName") private String cityName; } ``` 测试用例 ``` public class Test { public static void main(String[] args) { String xml = "<BizContent><CityCode>123</CityCode><CityName>城市名称</CityName></BizContent>"; AA aa = XStreamUtil.xmlToObject(xml, AA.class); System.out.println(aa); String toXml = XStreamUtil.objectToXml(aa); System.out.println(toXml); } } ```
我的主页
退出