2014-02-10 39 views
1

我有下面的代碼映射到Java類:如何自動JSON在Spring控制器

public class MyClass { 

    String xxx; 
    String yyy; 

    public String getXxx() { 
     return xxx; 
    } 
    public void setXxx(String xxx) { 
     this.xxx = xxx; 
    } 
    public String getYyy() { 
     return yyy; 
    } 
    public void setYyy(String yyy) { 
     this.yyy = yyy; 
    } 
    public MyClass(String xxx, String yyy) { 
     super(); 
     this.xxx = xxx; 
     this.yyy = yyy; 
    } 

    @Override 
    public String toString() { 
     return "MyClass [xxx=" + xxx + ", yyy=" + yyy + "]"; 
    } 
} 

我還實施了服務:

import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestBody; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.ResponseBody; 


@Controller 
class MyService { 

    @RequestMapping(value = "/abc", method = RequestMethod.POST, produces = "application/json") 

    public @ResponseBody 
    String add(@RequestBody String myClass, HttpServletRequest request, 
     HttpServletResponse response) { 

     return "Test"; 
    } 

} 

當我做一個HTTP調用DEV HTTP客戶端JSON:

{"xxx":"abc", "yyy":"abc"}

enter image description here

我看到一個錯誤:

Error 406 NOT_ACCEPTABLE

是否有可能做這樣或我有編碼JSON和創建Java對象?

+2

你有傑克遜庫(http://jackson.codehaus.org /)在你的類路徑中可用?這應該是無縫的,當他們在場(相對香草配置)。 –

+0

不,不是,但我不確定它是否是解決方案 – ruhungry

+0

您一直使用字符串代替班級。 '@ ResponseBody'通常應該返回代表JSON響應的POJO。另外,顯式設置'produce'值是多餘的(並且防止Spring返回XML,以防重要)。 – chrylis

回答

4

嘗試添加產生= 「應用/ JSON」@RequestMapping

import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestBody; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.ResponseBody; 


@Controller 
class MyService { 

@RequestMapping(value = "/abc", method = RequestMethod.POST,produces = "application/json") 
    public @ResponseBody String myMethod(@RequestBody String _json,HttpServletRequest request, 
     HttpServletResponse response) { 
     return _json; 
    } 
} 

this the result with postman extension for chrome

+0

仍然無效。也許我從DEV HTTP CLIENT發送的數據有問題... – ruhungry

+1

添加到myMethod構造函數請求和響應中,並在String中更改myClass的類型。然後解析myClass中的字符串。 – sagat

+1

myMethod(@RequestBody String myClass,HttpServletRequest請求, HttpServletResponse響應) – sagat

1

你可以做到這一點與谷歌GSON在你的控制器。

這裏是例子:

  Gson gson = new Gson(); 
      JsonElement s = gson.toJsonTree(device, Devices.class); 
      return s.toString(); 

,不要忘了

@ResponseBody

希望這將是有益的

相關問題