Как автоматически сопоставить JSON с классом Java в Spring Controller

Я получил следующий код:

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 CLIENT с JSON:

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

Я вижу ошибку:

Ошибка 406 NOT_ACCEPTABLE

Можно ли сделать это таким образом, или я должен кодировать JSON и создать объект Java?

2 ответа

Решение

Попробуйте добавить продукцию "application/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;
    }   
}

это результат с расширением почтальона для хрома

Вы можете сделать это с помощью Google GSON в вашем контроллере.

вот пример:

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

и не забудьте для @ResponseBody

Надеюсь, это будет полезно

Другие вопросы по тегам