2015-03-31 142 views
4

我遇到了Jackson序列化User Box對象的問題。 有一些私人領域與getter和setters。一切工作正常,當我做這樣的事情:Jackson 2和Spring Autowired bean

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

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

但我想自動裝配用戶對象與Spring框架:

@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"] 
... 

看起來像春天做錯了什麼用自動裝配的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; 
    } 
} 
+0

您的用戶是否包含對用戶有引用的字段? – JEY 2015-03-31 15:03:33

+0

請分享你的MyUser類 – Mithun 2015-03-31 15:10:07

+0

我已經更新了我的問題whit MyUser類。謝謝。 – 2015-03-31 15:22:19

回答

2

由於您使用MyUser作爲一個Spring管理的bean,春包裝你的對象爲代理 - 所以,當你調用mapper.writeValueAsString(user);你實際上是在傳遞作爲參數的代理。該代理包含一些屬性,該映射器無法序列化。

您可以嘗試序列化之前將過濾器只包含您需要的屬性:

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

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

是的,它的工作原理。謝謝。 – 2015-03-31 16:04:09

+0

但是,如果我在MyUser類中有20個字段呢?而且這些字段可能稍後會修改。是否有另一種序列化Autowired POJO的方法? – 2015-03-31 16:10:19

+0

@ silent-box可能有其他方法 - 但我還沒有遇到過這種情況,所以我不能確定。可能有一些方法可以告訴映射器將對象作爲超類來處理 - 即'MyUser'或者一些具有相似含義的@Json ...'註釋。 – Vladimir 2015-03-31 16:15:56

1

此例外是UnknownSerializer類拋出。下面是引發異常的確切代碼:

throw new JsonMappingException("No serializer found for class "+value.getClass().getName() 
    +" and no properties discovered to create BeanSerializer 
    (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS))"); 

錯誤消息附加了它無法序列化的類的名稱。在你的情況下,根據錯誤消息,問題是org.apache.juli.OneLineFormatter類。因此,MyUser類沒有問題。

現在來解釋這個錯誤的原因,當序列化所有字段爲私有的實體時,會引發此錯誤。在org.apache.juli.OneLineFormatter類中,所有字段都是私有的,沒有任何公共的getter和setter方法。

+0

我認爲從他的描述中可以清楚地看到他的領域有公開的獲得者和接球手。 – user2076066 2016-01-14 09:37:14