Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json Serializing JDK Dynamic Proxy with Jackson library

I'm trying to serialize a Java Dynamic proxy using Jackson library but I get this error:

public interface IPlanet {
String getName();
}

Planet implements IPlanet {
    private String name;
    public String getName(){return name;}
    public String setName(String iName){name = iName;}
}

IPlanet ip = ObjectsUtil.getProxy(IPlanet.class, p);
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(ip);

//The proxy generation utility is implemented in this way:
/**
 * Create new proxy object that give the access only to the method of the specified
 * interface.
 * 
 * @param type
 * @param obj
 * @return
 */
public static <T> T getProxy(Class<T> type, Object obj) {
    class ProxyUtil implements InvocationHandler {
        Object obj;
        public ProxyUtil(Object o) {
            obj = o;
        }
        @Override
        public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
            Object result = null;
            result = m.invoke(obj, args);
            return result;
        }
    }
    // TODO: The suppress warning is needed cause JDK class java.lang.reflect.Proxy
    // needs generics
    @SuppressWarnings("unchecked")
    T proxy = (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type },
            new ProxyUtil(obj));
    return proxy;
}

I get this exception:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class $Proxy11 and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.SerializationFeature.FAIL_ON_EMPTY_BEANS) )

The problem seems to be the same that happens when hibernate proxied objects are serialized but I don't know how and if I can use the Jackson-hibernate-module to solve my issue.

UPDATE: The BUG was solved from Jackson 2.0.6 release

like image 712
carlo.polisini Avatar asked Aug 24 '12 15:08

carlo.polisini


1 Answers

You can try Genson library http://code.google.com/p/genson/. I just tested your code with it and it works fine the output is {"name":"foo"}

Planet p = new Planet();
p.setName("foo");
IPlanet ip = getProxy(IPlanet.class, p);
Genson genson = new Genson();
System.out.println(genson.serialize(ip));

It has a couple of nice features that do not exisit in other librairies. Such as using constructor with arguments without any annotation or applying what is called BeanView on your objects at runtime (acts a as view of your model), can deserialize to concrete types, and more... Take a look at the wiki http://code.google.com/p/genson/wiki/GettingStarted.

like image 194
eugen Avatar answered Sep 22 '22 18:09

eugen