【问题标题】:Json Serializing JDK Dynamic Proxy with Jackson libraryJson 使用 Jackson 库序列化 JDK 动态代理
【发布时间】:2012-08-20 04:54:44
【问题描述】:

我正在尝试使用 Jackson 库序列化 Java 动态代理,但出现此错误:

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;
}

我得到了这个例外:

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) )

问题似乎与休眠代理对象序列化时发生的相同,但我不知道如何以及是否可以使用 Jackson-hibernate-module 来解决我的问题。

更新: 该BUG已从Jackson 2.0.6 版本解决

【问题讨论】:

  • 这里关于“p”的快速问题——它是什么类型的? (行星?)。另外,Planet 是否应该实现 IPlanet:如果是,代理有什么好处?

标签: java json jackson dynamic-proxy


【解决方案1】:

你可以试试 Genson 库http://code.google.com/p/genson/。 我刚刚用它测试了你的代码,它工作正常输出是 {"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));

它具有其他库中不存在的几个不错的功能。 例如在没有任何注释的情况下使用带参数的构造函数,或者在运行时在对象上应用所谓的 BeanView(充当模型的视图),可以反序列化为具体类型,等等……看看 wiki http://code.google.com/p/genson/wiki/GettingStarted .

【讨论】:

  • 非常非常好,您的库给我留下了深刻的印象(因为您似乎是开发人员)!我看了文档,很清楚,我想说你做得很好,很多注释也类似于杰克逊库,这有助于最终迁移。
  • 非常感谢,很高兴您欣赏我的工作。
【解决方案2】:

这可能是 Jackson 中的一个错误——代理类可能被明确禁止被视为 bean。你可以提交一个错误——如果 Genson 可以处理它,Jackson 也应该。 :-)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
相关资源
最近更新 更多