Jackson 2和Spring Autowired bean [英] Jackson 2 and Spring Autowired bean
问题描述
我遇到了我的User对象的Jackson序列化问题。
有一些私人领域有getter和setter。当我做这样的事情时一切正常:
I've encountered a problem with Jackson serialization for my User object. There are a few private fields with getters and setters. And everything works fine when I do something like this:
public String json() {
MyUser user = new MyUser();
user.setUsername("myName");
return mapper.writeValueAsString(user); // Valid JSON
}
但我想用Spring Framework自动装配User对象:
But i'd like to autowire User object with Spring Framework:
@Autowired
private MyUser user;
public String json() {
System.out.println(user.getUsername()); // Property set before and it works
return mapper.writeValueAsString(user); // Error
}
这不起作用。我有一个错误:
And this doesn't work. I've got an error:
com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.apache.juli.OneLineFormatter and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.piggymetrics.classes.PiggyUser$$EnhancerBySpringCGLIB$$5f23855e["targetSource"]->org.springframework.aop.target.SimpleBeanTargetSource["beanFactory"]->org.springframework.beans.factory.support.DefaultListableBeanFactory["parentBeanFactory"]->org.springframework.beans.factory.support.DefaultListableBeanFactory["beanClassLoader"]->org.apache.catalina.loader.WebappClassLoader["resources"]->org.apache.catalina.webresources.StandardRoot["context"]->org.apache.catalina.core.StandardContext["logger"]->org.apache.juli.logging.DirectJDKLog["logger"]->java.util.logging.Logger["parent"]->java.util.logging.Logger["handlers"]->org.apache.juli.AsyncFileHandler["formatter"])
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:59)
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:26)
当我尝试忽略这些未知错误时
And when i try to ignore these unknown errors
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
我得到了无限递归:
com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: org.apache.catalina.core.StandardEngineValve["container"]->org.apache.catalina.core.StandardEngine["pipeline"]->org.apache.catalina.core.StandardPipeline["basic"]->org.apache.catalina.core.StandardEngineValve["container"]
...
看起来Spring在自动装配的MyUser实例上做错了,所以Jackson无法将其序列化。
Looks like Spring did something wrong with autowired MyUser instance so Jackson can't serialize it.
有没有办法解决它?
UPDATE
MyUser类非常简单:
MyUser class is pretty simple:
package com.metrics.classes;
import com.metrics.classes.interfaces.User;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyUser implements User {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
推荐答案
自你使用 MyUser
作为Spring托管bean,Spring将你的对象包装成代理 - 所以当你调用 mapper.writeValueAsString(user);
您实际上是在传递代理作为参数。所述代理包含一些属性,映射器无法序列化。
Since you use MyUser
as a Spring managed bean, Spring wraps your object into a proxy - so when you are calling mapper.writeValueAsString(user);
you are actually passing a proxy as argument. Said proxy contains some properties, that mapper cannot serialize.
您可以尝试在序列化之前应用过滤器以仅包含您需要的属性:
You can try applying filter before serialization to include only the properties you need:
ObjectMapper mapper = new ObjectMapper();
SimpleFilterProvider simpleFilterProvider = new SimpleFilterProvider()
.addFilter("myUser", simpleBeanPropertyFilter.filterOutAllExcept("username"));
mapper.setFilters(filterProvider);
return mapper.writeValueAsString(user);
这篇关于Jackson 2和Spring Autowired bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!