我有下面的代碼映射到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"}
我看到一個錯誤:
Error 406 NOT_ACCEPTABLE
是否有可能做這樣或我有編碼JSON和創建Java對象?
你有傑克遜庫(http://jackson.codehaus.org /)在你的類路徑中可用?這應該是無縫的,當他們在場(相對香草配置)。 –
不,不是,但我不確定它是否是解決方案 – ruhungry
您一直使用字符串代替班級。 '@ ResponseBody'通常應該返回代表JSON響應的POJO。另外,顯式設置'produce'值是多餘的(並且防止Spring返回XML,以防重要)。 – chrylis