如何在Spring Controller中自动将JSON映射到Java类

时间:2014-02-10 15:27:27

标签: java json spring rest http-status-code-415

我有以下代码:

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";
    }

}

当我使用带有JSON的DEV HTTP CLIENT进行HTTP调用时:

  

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

enter image description here

我看到一个错误:

  

错误406 NOT_ACCEPTABLE

是否可以这样做,或者我必须编码JSON并创建Java对象?

2 个答案:

答案 0 :(得分:4)

尝试在 @RequestMapping 中添加 produce =“application / json”

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

答案 1 :(得分:1)

你可以在你的控制器中使用谷歌GSON。

这里是例子:

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

并且不要忘记@ResponseBody

希望它会有所帮助