XStream parse attributes and values at the same time

雨燕双飞 提交于 2019-12-04 05:48:40
gurbieta

I finally found the solution, a Converter solves this, here is the code

public class CityConverter implements Converter {

    public void marshal(Object value, HierarchicalStreamWriter writer, 
                                                               MarshallingContext context) {
        City city = (City) value;
        writer.addAttribute("id", city.getId());
        writer.addAttribute("type", city.getType().toString());
        writer.setValue(city.getName());
    }

    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        City city = new City();
        city.setName(reader.getValue());
        city.setId(reader.getAttribute("id"));
        city.setType(reader.getAttribute("type"));
        return city;
    }

    public boolean canConvert(Class clazz) {
        return clazz.equals(City.class);
    }

}

And in the part of setting the aliases I also set up the CityConverter

xStream.registerConverter(new CityConverter());
xStream.alias("search", List.class);
xStream.alias("loc", City.class);

And all works fine :)

Jay Walters

I am posting this in hopes that it might help others because it took me quite some time to find it... http://fahdshariff.blogspot.com/2011/12/using-xstream-to-map-single-element.html

The answer is to use @XStreamConverter - ToAttributedValueConverter

@XStreamAlias("error")
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"message"})
public class Error {

  String message;

  ...

There are lots of interesting converters that provide all sorts of useful functionalities... http://x-stream.github.io/converters.html

XStream seems kind of complicated, you could do the following in JAXB:

public class City { 

    @XmlAttribute private String  id; 
    @XmlAttribute private Integer type; 
    @XmlValue private String  name; 

    // getters & setters... 
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!