2016-02-18 49 views
0

如何自動解析json到post請求中的多個參數以及內容類型是「application/json」? 例如,我有這樣一個控制器的方法:在post請求中使用spring解析json內容到多個參數中mvc

@RequestMapping(value = "/test", method = RequestMethod.POST) 
public Object testPost(@RequestBody Student student) { 
    return student; 
} 

「學生」 類是:

public class Student { 
    private Integer id; 
    private String name; 
    getter&setter 
} 

和JSON是:

{"student":{"id":1,"name":"測試"}} 

控制器返回空物體(當然不是null,而「id」和「name」屬性爲空)。 我知道什麼時候該JSON是它的工作:

{"id":1,"name":"測試"} 

或扭曲我的學生在其他類中的「學生」的領域,但我不能這樣做。 我發現它不能使用@RequestParams或@ModelAttribute,因爲在RequestParamMethodArgumentResolver和ModelAttributeMethodProcessor中,它們只能在ServletRequest#getParameter中找到值。 那麼,春天mvc能解決這個問題還是我只能做這個習慣? (請原諒我,我的英語很糟糕......)


感謝幫助,我不能完成的學生,因爲我使用的是公司內部的工具,也許這不是一個很常見的功能,使我決定寫一個自定義參數解析器(HandlerMethodArgumentResolver)。

+0

_「將學生包裹在其他班的」學生「字段,但我不能這樣做」_爲什麼不呢?如果你不能這樣做,那麼你也不能做其他事情。 – zeroflagL

+0

@zeroflagL他可以使用@ ModelAttribute – achabahe

+0

@achabahe我已經嘗試@ ModelAttribute,並且我讀過源代碼,你可以發現@ ModelAttribute只讀請求#getParameterMap用於解析代碼中的參數:ModelAttributeMethodProcessor#resolveArgument- > DefaultDataBinderFactory#createBinderInstance-> WebRequestDataBinder#bind –

回答

0

嘗試將「學生」對象封裝在某個其他對象內。對於當前實現,你正在做的JSON應該像

{「ID」:1,「名」:「測試」}

但是,如果您要發送JSON的控制器

{「student」:{「id」:1,「name」:「測試」}}

然後它必須包裝在JSON解析器的另一個Java類中才能正確解析它。

+0

是的,我知道它可以工作,但我受到公司內部工具的限制,我無法更改JSON。所以我決定自定義... –

+0

您的自定義實現是否適合您?或者你仍然在解決這個問題? – Shriram

+0

是的,我做了一個自定義的實現,它的工作原理,謝謝。 –

0

你可以在請求得到方法處理之前對待json messsage,在treat body中你可以將你的json字符串轉換爲學生對象然後返回它,那個學生對象將被保存在名爲student的requestAttribute中檢索它在你的testPost

@RequestMapping(path="/test", method = RequestMethod.POST) 
public String testPost(@ModelAttribute("student") Student student) { 
    System.out.println("student->" + student); 

    return "response"; 

} 

@ModelAttribute("student") 
public Student treatBody(@RequestBody String body) { 
    //retrieve student from json 
    return student; 
} 
+0

是的,這可能是work.I忘記說我想要一個常見的功能來自動分析像@ RequestParam工作的對象。 –