I experimented with Jackson 2.0 mixins to serialize a class without annotations.
Simplified source code below. Please note that I do not use getters / seters, but it seems that I can still use mixins according to some rather fragmentary documentation .
public class NoAnnotation { private Date created; private String name; private int id; private List<URL> urls = new ArrayList(); // make one with some data in it for the test static NoAnnotation make() { NoAnnotation na= new NoAnnotation(); na.created = new Date(); na.name = "FooBear"; na.id = 23456; try { na.urls.add(new URL("http://www.eclipse.org/eclipselink/moxy.php")); na.urls.add(new URL("http://jaxb.java.net")); } catch (MalformedURLException e) { throw new RuntimeException(e); } return na; } // my Mixin "Class" static class JacksonMixIn { JacksonMixIn(@JsonProperty("created") Date created, @JsonProperty("name") String name, @JsonProperty("id") int id, @JsonProperty("urls") List<URL> urls) { /* do nothing */ } } // test code public static void main(String[] args) throws Exception { NoAnnotation na = NoAnnotation.make(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.addMixInAnnotations(NoAnnotation.class, JacksonMixIn.class); String jsonText = objectMapper.writeValueAsString(na); System.out.println(jsonText); } }
When I launch the main, I get
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class com.flyingspaniel.so.NoAnnotation and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.SerializationFeature.FAIL_ON_EMPTY_BEANS) ) at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:51) at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:25) at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:108) at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:2407) at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:1983) at com.flyingspaniel.so.NoAnnotation.main(NoAnnotation.java:49)
I assume that I am leaving the basic "setThis" step somewhere, but I don't know what. Thanks!
EDIT: When I follow the instructions in Exception and add the line
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
I no longer get the exception, but the result is an empty JSON string, "{}".
EDIT2: if I create the fields public, this works, but this is not a reasonable object design.
source share