json序列化

wsewodh2  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(415)

我试图使用jackson库序列化java动态代理,但出现以下错误:

  1. public interface IPlanet {
  2. String getName();
  3. }
  4. Planet implements IPlanet {
  5. private String name;
  6. public String getName(){return name;}
  7. public String setName(String iName){name = iName;}
  8. }
  9. IPlanet ip = ObjectsUtil.getProxy(IPlanet.class, p);
  10. ObjectMapper mapper = new ObjectMapper();
  11. mapper.writeValueAsString(ip);
  12. //The proxy generation utility is implemented in this way:
  13. /**
  14. * Create new proxy object that give the access only to the method of the specified
  15. * interface.
  16. *
  17. * @param type
  18. * @param obj
  19. * @return
  20. */
  21. public static <T> T getProxy(Class<T> type, Object obj) {
  22. class ProxyUtil implements InvocationHandler {
  23. Object obj;
  24. public ProxyUtil(Object o) {
  25. obj = o;
  26. }
  27. @Override
  28. public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
  29. Object result = null;
  30. result = m.invoke(obj, args);
  31. return result;
  32. }
  33. }
  34. // TODO: The suppress warning is needed cause JDK class java.lang.reflect.Proxy
  35. // needs generics
  36. @SuppressWarnings("unchecked")
  37. T proxy = (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type },
  38. new ProxyUtil(obj));
  39. return proxy;
  40. }

我有个例外:

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

问题似乎与hibernate代理对象序列化时发生的问题相同,但我不知道如何以及是否可以使用jacksonhibernate模块来解决问题。
更新:jackson2.0.6版本解决了这个bug

tzxcd3kk

tzxcd3kk1#

这可能是jackson中的一个bug——代理类可能被显式地阻止被认为是bean。你可以提交一个bug——如果genson能处理,jackson也应该提交

brgchamk

brgchamk2#

你可以试试根森图书馆http://code.google.com/p/genson/. 我刚刚用它测试了您的代码,它运行良好输出是{“name”:“foo”}

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

它有一些在其他库中不存在的特性。例如,在没有任何注解的情况下使用带参数的构造函数,或者在运行时对对象应用所谓的beanview(充当模型的视图),可以反序列化为具体类型,等等。。。看看维基http://code.google.com/p/genson/wiki/gettingstarted.

相关问题