2011-02-15 84 views
13

我運行Jersey REST服務。代表我資源的POJO是JAXB(XML)註釋的簡單Java類(它們是從模式定義生成的 - 因此它們具有註釋)。配置澤西/傑克遜不使用@XmlElement字段註釋JSON字段命名

我希望Jersey/Jackson忽略XML-Annotations。我做這個配置在我的web.xml(如提及here):

<init-param> 
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> 
    <param-value>true</param-value> 
    </init-param> 

我現在預計@XmlElement註釋將不再被用於JSON字段命名策略使用。

但看這個Java字段(成員)

@XmlElement(name = "person", required = true) 
protected List<Person> persons; 

我仍然得到以下JSON表示:

....,"person":[{"name":"FooBar", ....... (person without the 's') 

所有其他領域也仍從@XmlElement註釋得到他們的JSON名稱,而不是來自Java字段名稱。

我想實現傑克遜Full Data Binding (POJO) Example中描述的JSON輸出。

它的工作原理是這樣簡單的測試罰款(我的XML註釋類):

ObjectMapper mapper = new ObjectMapper(); 
    mapper.writeValue(System.out, myObject); 

而是嵌入在新澤西,我沒有得到預期的JSON輸出。

澤西島的其他配置選項是否獲得'簡單'的POJO JSON表示(因爲這最適合需要反序列化JSON結果的客戶端)。

由於克勞斯

詳細溶液

(1)實施爲ContextResolver傑克遜ObjectMapper創建將不會使用註釋的ObjectMapper。

package foo.bar.jackson; 

import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.ext.ContextResolver; 
import javax.ws.rs.ext.Provider; 

import org.codehaus.jackson.map.DeserializationConfig; 
import org.codehaus.jackson.map.ObjectMapper; 
import org.codehaus.jackson.map.SerializationConfig; 

/** 
* Customized {@code ContextResolver} implementation that does not use any 
* annotations to produce/resolve JSON field names. 
*/ 
@Provider 
@Produces(MediaType.APPLICATION_JSON) 
public class JacksonContextResolver implements ContextResolver<ObjectMapper> { 

    private ObjectMapper objectMapper; 

    /** 
    * Creates a new instance. 
    * 
    * @throws Exception 
    */ 
    public JacksonContextResolver() throws Exception { 
     this.objectMapper = new ObjectMapper().configure(
       DeserializationConfig.Feature.USE_ANNOTATIONS, false) 
       .configure(SerializationConfig.Feature.USE_ANNOTATIONS, false); 
     ; 
    } 

    /** 
    * @see javax.ws.rs.ext.ContextResolver#getContext(java.lang.Class) 
    */ 
    public ObjectMapper getContext(Class<?> objectType) { 
     return objectMapper; 
    } 
} 

(2)在你的application.xml

<bean class="foo.bar.jackson.JacksonContextResolver"/> 

回答

6

在較低水平,以確保ObjectMapper不使用JAXBAnnotationIntrospector所需要的註冊ContextResolver的Spring bean,但只能默認JacksonAnnotationIntrospector。我認爲你應該能夠構建ObjectMapper(默認情況下不添加JAXB introspector),並通過標準的JAX-RS提供者機制註冊它。這應該覆蓋POJO映射器功能將以其他方式構建的ObjectMapper。

+0

謝謝,這是解決方案 - 雖然我不知道該怎麼做沒有很多其他類似的SO問題/答案我發現:-)我會在問題中發佈詳細的解決方案。 – FrVaBe 2011-02-16 08:08:47