Xstream Implicit Map As Attributes to Root Element

前端 未结 1 471
甜味超标
甜味超标 2021-01-16 05:29

I am trying to find a solution to convert a map into root element attributes using XStream.

I do not think this is possible but here is what I have tried to far.

相关标签:
1条回答
  • 2021-01-16 05:53

    Create a converter that writes out the map and falls back on marshalling the object using a reflection converter:

    static class MyConverter implements Converter {
    
        private final Map<String, String> attributes;
    
        private final Class<?> clazz;
    
        private final Mapper mapper;
    
        private final ReflectionProvider reflectionProvider;
    
        public MyConverter(Mapper mapper,
                ReflectionProvider reflectionProvider, Class<?> clazz,
                Map<String, String> attributes) {
            super();
            this.mapper = mapper;
            this.reflectionProvider = reflectionProvider;
            this.attributes = attributes;
            this.clazz = clazz;
        }
    
        @Override
        public boolean canConvert(Class cls) {
            return cls == clazz;
        }
    
        @Override
        public void marshal(Object value, HierarchicalStreamWriter writer,
                MarshallingContext context) {
            for (String key : attributes.keySet()) {
                writer.addAttribute(key, attributes.get(key));
            }
    
            Converter converter = new ReflectionConverter(mapper,
                    reflectionProvider);
            context.convertAnother(p, converter);
        }
    
        @Override
        public Object unmarshal(HierarchicalStreamReader arg0,
                UnmarshallingContext arg1) {
            // TODO Auto-generated method stub
            return null;
        }
    
    }
    

    Retrieve the Mapper and ReflectionProvider instances from your XStream instance, and register a converter with all necessary setup:

        XStream xs = new XStream(new DomDriver());
        Mapper mapper = xs.getMapper();
        ReflectionProvider reflectionProvider = xs.getReflectionProvider();
        xs.alias("youralias", YourRoot.class);
        xs.registerConverter(new MyConverter(mapper, reflectionProvider,
                YourRoot.class, map));
    
        System.out.println(xs.toXML(yourRoot));
    
    0 讨论(0)
提交回复
热议问题