簡體   English   中英

Spring MVC使用傑克遜解析對象?

[英]Spring mvc parse object using jackson?

我的豆類,

import java.util.LinkedList;

public class Information {

    private LinkedList<String> information ;

    public LinkedList<String> getInformation() {
        return information;
    }

    public void setInformation(LinkedList<String> information) {
        this.information = information;
        System.out.println("List is : "+information);
    }


}

我的控制器,

@RequestMapping(value="/registerDn.html",method=RequestMethod.POST)
public @ResponseBody Information registerDn( @RequestParam(value = "dn", required = false) String dn,
        @RequestParam(value = "acd", required = false) String acd ){
    System.out.println("DN is : "+dn+   "    acd : "+acd);
    WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    UserOperation oper = (UserOperation)ctx.getBean("operation");
    oper.registerDn(dn);

    Information info = (Information) ctx.getBean("info");
    return info;
}

我的jQuery將是,

function registerDn(){

    $.ajax({  
        type: "POST",  
        url: contexPath + "/registerDn.html",
        data: "dn=" + dn + "&acd=" + acd,  
        success: function(response){

            var userInfo = "<ol>";

            for( i =0 ; i < response.information.length ; i++){
                userInfo += "<br><li><b>Name</b> : " + response.information[i] ;
            }

            userInfo += "</ol>";

            //Used to display the list
            $('#getlist').html(dn + " is : " + userInfo); 

        },  
        error: function(e){  
            alert('Error: ' + e);  
        }, 

    }); 

} 

我在jquery-ajax中獲得成功,但是不知道如何解析它並在視圖中顯示它。

或單擊按鈕時如何使用jquery-ajax在Bean類中獲取列表。

好的答案肯定會受到贊賞。

示例代碼中沒有任何內容表明響應應該是/應該是JSON對象。

  1. Jackson jar必須位於類路徑上,以便在應用程序的上下文中配置MappingJackson HttpMessageConverter
  2. jQuery的AJAX配置應具有的dataType定義為JSON或使用produces的的屬性@RequestMapping注釋和設定的值作為application/json

基本上,如果Spring知道響應內容類型應該為json,它將使用Jackson映射轉換器將pojo轉換為JSON,然后jQuery成功回調將獲得JSON對象。

您應該確切地看到FireBug發生了什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM