2012-01-16 66 views
0

我試圖處理下面春3 MVC的JSON:處理複雜的JSON與Spring MVC 3

var fields = { 
    "fields" : [ { 
     "groupId" : "mission", 
     "type" : "text", 
     "id" : "company_name", 
     "label" : "Nom de l'entreprise", 
     "size" : 0 
    }, { 
     "groupId" : "mission", 
     "type" : "text", 
     "id" : "theme", 
     "label" : "Thème", 
     "size" : 0 
    }, { 
     "groupId" : "mission", 
     "type" : "textarea", 
     "id" : "descriptive", 
     "label" : "Description", 
     "size" : 0 
    } ] 
}; 

這是我如何把它:

$.ajax({ 
    type: "POST", 
    url: "/GestaWeb/internshipConfiguration/proposal", 
    data: fields 
}).done(function(msg) { 
    alert("Data Saved: " + msg); 
}); 

通過HTTP傳遞的PARAMS (它的Chrome網絡開發者控制檯中的副本):

fields[0][groupId]:mission 
fields[0][type]:text 
fields[0][id]:company_name 
fields[0][label]:Nom de l'entreprise 
fields[0][size]:0 
fields[1][groupId]:mission 
fields[1][type]:text 
fields[1][id]:theme 
fields[1][label]:Thème 
fields[1][size]:0 
fields[2][groupId]:mission 
fields[2][type]:textarea 
fields[2][id]:descriptive 
fields[2][label]:Description 
fields[2][size]:0 

而且我的春節,3 MVC控制器:

package controller.internshipConfiguration; 

import org.springframework.stereotype.Controller; 
import org.springframework.ui.ModelMap; 
import org.springframework.web.bind.annotation.*; 
import org.springframework.web.servlet.*; 

@Controller 
@RequestMapping(value = "/internshipConfiguration") 
public class ProposalModelConfigurationController { 

    @RequestMapping(value = "/proposal", method = RequestMethod.GET) 
    public ModelAndView form(ModelMap model) { 
     System.out.println("internship config view"); 
     return new ModelAndView("internship/formModel"); 
    } 

    @RequestMapping(value="/proposal", method = RequestMethod.POST) 
    public @ResponseBody String form(@RequestParam(value="fields") String fields) { 

     System.out.println("Fields rofl: " + fields); 

     return "ok"; 
    } 

} 

當我執行阿賈克斯我有一個400 如果我通過一個簡單的對象喜歡這個工作得很好:{字段:「富」}

回答

0

集的contentType到JSON在年Ajax調用:

$.ajax({ 
    type: "POST", 
    url: "/GestaWeb/internshipConfiguration/proposal", 
    data: fields, 
    contentType: "application/json" 
}).done(function(msg) { 
    alert("Data Saved: " + msg); 
}); 

你還應該創建一個java類,以匹配字段 - 傑克遜/春將自動提供類。所以年控制器想這樣的事情:

@RequestMapping(value="/proposal", method = RequestMethod.POST) 
public @ResponseBody String form(@RequestBody MyPojoForFields myPojoForFields){} 

MyPojoForfields通常是域對象或DTO。

我還沒有嘗試過自己,但我也猜測提供List作爲方法的參數也沒關係。

更多閱讀here

+0

我試着用List作爲參數類型,現在我得到了415。 – DevAntoine 2012-01-16 19:29:18