Tuesday, 17 September 2013

Is it possible to use Jackson JSON to serialize a custom annotation?

Is it possible to use Jackson JSON to serialize a custom annotation?

I have created a simple annotation for a class' methods. I would like to
export the value of each annotation in JSON format.
So for example, I have an annotation:
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface MyAnnotation
{
int someInteger();
String someString();
String[] possibleTypes();
}
And then in my class I am annotating I have:
package com.clusin;
public class foo
{
@MyAnnotation(someInteger = 1, someString = "bar", possibleType = {
"a","b","c" })
public int doSomeComputation(Object x, Object y)
{
//Do something here.
}
}
Using reflection we can obtain a reference to these annotations at runtime.
So my question is: Given these annotations obtained at run time, is it
possible to use jackson to serialize the values contained in the
annotation?
I've tried annotating my annotation with @JsonProperty but the
ObjectMapper throws a JsonMappingException when calling
ObjectMapper#writeValueAsString.
org.codehaus.jackson.map.JsonMappingException: No serializer found for
class $Proxy5 and no properties discovered to cre
ate BeanSerializer (to avoid exception, disable
SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )
at
org.codehaus.jackson.map.ser.StdSerializerProvider$1.failForEmpty(StdSerializerProvider.java:89)
at
org.codehaus.jackson.map.ser.StdSerializerProvider$1.serialize(StdSerializerProvider.java:62)
at
org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:315)
at
org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:242)
at
org.codehaus.jackson.map.ObjectMapper._configAndWriteValue(ObjectMapper.java:1846)
at
org.codehaus.jackson.map.ObjectMapper.writeValueAsString(ObjectMapper.java:1473)
Any ideas?
Thanks for your time.

No comments:

Post a Comment