Change fields order when using XStream

xstream_field_order
1. XMLSequence : annotation which will be used for TestXml class
2. TestXml : Class for xstream fields
3. PartialSeqFieldKeySorter: customize the sort fields, defined fields which you will display in XML

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();
            Map custom = 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;
        }
    }
}


Leave a Reply

Your email address will not be published. Required fields are marked *