Friday, March 8, 2013

Convert java attributes to start with upperCase when being written to xml file using XStream

    if (xstream == null) {
                xstream = new XStream(){
                  
                    @Override
                    protected MapperWrapper wrapMapper(MapperWrapper next) {
                            return new UpperCaseMapper(next);
                    }
                };
            }
           
    private static class UpperCaseMapper extends MapperWrapper {
        public UpperCaseMapper(Mapper wrapped) {
                super(wrapped);
        }

        @Override
        public String serializedMember(Class type, String memberName) {
            String camelCase = memberName.substring(0, 1).toUpperCase() + memberName.substring(1);
            return super.serializedMember(type, camelCase);
        }
       
        @Override
        public String realMember(Class type, String serialized) {
                String camelCase = serialized.substring(0, 1).toLowerCase()
                                + serialized.substring(1);
                return super.realMember(type, camelCase);
        }
    }

No comments: