针对list类型的自定义Converter进行优化,提供参数实现Converter的复用。
首选对自定义Converter进行改造
public class OrgIDConverter implements Converter { // 节点名称 private String nodeName; // 构造方法 public OrgIDConverter(String nodeName) { super(); this.nodeName = nodeName; } @SuppressWarnings("unchecked") public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext arg2) { // 将Object向下转型,因为有canConvert方法的判断,所以不用instanceOf判断 List<String> list = (List<String>) value; for (String subval : list) { // 将属性转换为自定义名称,不同的List集合只用在converter声明时提供参数即可 writer.startNode(nodeName); writer.setValue(subval); writer.endNode(); } } public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { // 声明List集合,用于接受xml的orgID元素并存储 List<String> list = new ArrayList<String>(); while (reader.hasMoreChildren()) { reader.moveDown(); String key = reader.getNodeName(); String value = null; // 这一步可以省略,直接使用else内容,if的内容是orgID下还有层元素,嵌套遍历 if (reader.hasMoreChildren()) { value = (String)unmarshal(reader, context); } else { value = reader.getValue(); } list.add(value); reader.moveUp(); } return list; } public boolean canConvert(Class type) { // 判断传入class的类型,注意:一定要使用声明类(List不能通过) return type.equals(ArrayList.class); } }
修改注册方法,在实体类中进行注册:
public class InfoTest { public static void main(String[] args) { XStream stream = new XStream(); stream.alias("info", Info.class); // 使用自定义Converter stream.registerLocalConverter(Info.class, "orgIDs", new OrgIDConverter("orgID")); stream.registerLocalConverter(Info.class, "roleIDs", new OrgIDConverter("roleID")); // stream.alias("orgID", String.class); // stream.alias("roleID", String.class); ///:xstream会已最后一个对String类型的名称,命名所有String类型 Info info = new Info(); List<String> orgIDs = new ArrayList<String>(); orgIDs.add("020120214"); orgIDs.add("020120215"); info.setOrgIDs(orgIDs); List<String> roleIDs = new ArrayList<String>(); roleIDs.add("020120216"); roleIDs.add("020120217"); info.setRoleIDs(roleIDs); System.out.println(stream.toXML(info)); } }