5

My web service returns data in both xml and json using Spring MVC. For json, spring uses Jackson and XStream for XML. However, XStream uses fields for serialization while Jackson uses methods (setter/getter).

I would like to include all/some getter in xml serialization. How can this be accomplished via a custom converter or annotation?

ltfishie
  • 2,917
  • 6
  • 41
  • 68

2 Answers2

5

You need to register a custom JavaBeanConverter, take a look at the unit tests here: https://fisheye.codehaus.org/browse/xstream/tags/XSTREAM_1_1_3/xstream/src/test/com/thoughtworks/xstream/converters/javabean/JavaBeanConverterTest.java?r=554

XStream xstream = new XStream();
xstream.registerConverter(new JavaBeanConverter(xstream.getClassMapper(), "class"), -20);

Credit goes to original thread at: http://xstream.10960.n7.nabble.com/How-to-use-public-accessor-instead-of-field-td1193.html

Leonard Brünings
  • 12,408
  • 1
  • 46
  • 66
1

If you make the fields public, Jackson can use them instead of getter/setter methods. There is also an annotation @JsonProperty to cause that.

public class KeyValuePair {

    @JsonProperty
    private int value;
    @JsonProperty
    private String key;
}

Or look here how to specify jackson to only use fields - preferably globally to understand:

 @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
Community
  • 1
  • 1
Lee Meador
  • 12,829
  • 2
  • 36
  • 42