import com.thoughtworks.xstream.converters.reflection.FieldKey; import com.thoughtworks.xstream.converters.reflection.FieldKeySorter; import com.thoughtworks.xstream.core.util.OrderRetainingMap; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; public class PartialSeqFieldKeySorter implements FieldKeySorter { @Override public Map sort(Class type, Map keyedByFieldKey) { Annotation sequence = type.getAnnotation(XMLSequence.class); if (sequence != null) { final String[] fieldsOrder = ((XMLSequence) sequence).value(); Mapcustom = new LinkedHashMap<>(); Map notCustom = new LinkedHashMap<>(); Set > fields = keyedByFieldKey.entrySet(); for (String fieldName : fieldsOrder) { if (fieldName != null) { for (Map.Entry fieldEntry : fields) { if (fieldName.equalsIgnoreCase(fieldEntry.getKey().getFieldName())) { custom.put(fieldEntry.getKey(), fieldEntry.getValue()); } } } } return custom; } else { return keyedByFieldKey; } } }
自定义XStream fields序列化顺序
1. XMLSequence : 注解用于TestXml class
2. TestXml : Class for xstream fields
3. PartialSeqFieldKeySorter: 自定义fields顺序,toXml输出