加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java – Jackson 2和Spring Autowired bean

发布时间:2020-12-15 01:42:35 所属栏目:大数据 来源:网络整理
导读:我遇到了我的User对象的Jackson序列化问题. 有一些私人领域有getter和setter.当我做这样的事情时,一切正常: public String json() { MyUser user = new MyUser(); user.setUsername("myName"); return mapper.writeValueAsString(user); // Valid JSON} 但

我遇到了我的User对象的Jackson序列化问题.
有一些私人领域有getter和setter.当我做这样的事情时,一切正常:

public String json() {
   MyUser user = new MyUser();
   user.setUsername("myName");

   return mapper.writeValueAsString(user); // Valid JSON
}

但是我想用Spring Framework自动装配User对象:

@Autowired
private MyUser user;

public String json() {
    System.out.println(user.getUsername()); // Property set before and it works
    return mapper.writeValueAsString(user); // 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)

当我试图忽略这些未知错误时

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实例上做错了,所以杰克逊无法将其序列化.

有办法解决吗?

UPDATE

MyUser类非常简单:

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)时;你实际上是通过代理作为参数.所述代理包含一些属性,即映射器无法序列化.

您可以尝试在序列化之前应用过滤器以仅包含所需的属性:

ObjectMapper mapper = new ObjectMapper();
SimpleFilterProvider simpleFilterProvider = new SimpleFilterProvider()
    .addFilter("myUser",simpleBeanPropertyFilter.filterOutAllExcept("username"));

mapper.setFilters(filterProvider);
return mapper.writeValueAsString(user);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读