2013-07-18 16 views
0

這是事情......我使用jtable(jquery)來顯示一些用戶數據。該組件需要帶有兩個字段的Json:結果和記錄。在我的控制器中,我有一個返回json的方法:如何使用MappingJacksonHttpMessageConverter獲得帶有Pascal封套的Json?

@RequestMapping(method=RequestMethod.POST, value="/getUsersInJson") 
public @ResponseBody String getUsersInJsonHandler(){ 
    ElementsInList<User> users = new ElementsInList<User>(); 
    users.setItems(userService.getUsers()); 
    return users; 
} 

ElementsInList類包含兩個字段:result和records。結果是獲取成功消息的字符串,記錄是參數化列表,其中包含用戶列表。我得到這個JSON:

「{」 結果 「:」 OK」, 「記錄」:[{ 「用戶名」: 「約翰」,

但我需要這樣的:

「{」 結果「:」 OK」, 「記錄」:[{ 「用戶名」: 「約翰」,...

這是我的映射:

<!-- Json converter bean --> 
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> 
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
    <property name="messageConverters"> 
     <list> 
     <ref bean="jacksonMessageConverter"/> 
     </list> 
    </property> 
</bean> 

我該怎麼辦呢?我檢查了一些帖子,但有舊版本。 我使用Spring 3,Spring MVC和jQuery。

回答

0

我解決了它通過使用JsonProperty註釋。你可以給傑克遜用來構建json字段的名字。這裏有一個與JTable中(jQuery的)一個例子:

public class ElementsInList<T> { 
    @JsonProperty("Result") 
    private String result = "OK"; 

    @JsonProperty("Records") 
    private List<T> records; 
    public String getResult() { 
     return result; 
    } 
    public void setResult(String result) { 
     this.result = result; 
    } 
    public List<T> getRecords() { 
     return records; 
    } 
    public void setRecords(List<T> records) { 
     this.records = records; 
    } 
} 

結果JSON是這樣的:{ 「結果」: 「OK」, 「記錄」:[{ 「角色名」: 「管理」 ...

但有更多關於這個註釋。查詢api獲取更多信息:http://fasterxml.github.io/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/package-summary.html

相關問題