gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:50:22 25 4
gpt4 key购买 nike

我有以下代码:

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

我看到一个错误:

Error 406 NOT_ACCEPTABLE

是否可以通过这种方式进行,或者我必须对 JSON 进行编码并创建一个 Java 对象?

最佳答案

尝试在@RequestMapping中添加produces="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

关于java - 如何在 Spring Controller 中自动将 JSON 映射到 Java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21681183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com