gpt4 book ai didi

java - Spring Web 服务不会读取 JSON

转载 作者:行者123 更新时间:2023-12-02 05:54:04 25 4
gpt4 key购买 nike

由于编辑问题似乎并没有增加更多答案,因此我将在新线程中继续提问。

问题是,我正在尝试使用 Spring 设置一个非常基本的 Web 服务,我应该能够通过 Java 向其发送 JSON。

但是我对 Spring 和一般的 Web 服务都很陌生,所以我不知道在哪里进行故障排除。

老问题:Getting a RESTful webservice with Spring to understand a JSON-string

现在我的 Controller 中有这个

@RequestMapping(value = "/toggleB")
public @ResponseBody String sendCommand(@RequestBody Ident ident) {
//body
}

Ident 类只有一个字符串作为变量,称为 IP。

发送此字符串

 {"IP":"192.168.1.9"}

返回代码 400。

事实是,我认为 build.gradle(或 pom.xml)中可能有问题或丢失。正确的 Gradle/Spring 项目应该如何组织?

我的主要方法是可运行的,如下所示:

 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan
@EnableAutoConfiguration
public class mainFile {
public static void main(String[] args) {
SpringApplication.run(mainFile.class, args);
}
}

我没有使用任何 bean 作为配置,这可能是我的程序失败的原因吗?

再次感谢您的回复!我希望这样继续我的问题没有违反规则,但我不知道如何提高旧问题。啊……刚接触一个网站的坏处,呵呵。

最佳答案

如果您在请求正文中发送 JSON,请将其设为 POST 或 PUT 请求,同时添加 header 以接受 json。将 Json 作为字符串获取,然后使用 Json 解析器将其解析为 JsonNode 或您想要的任何内容。最后返回一个ResponseEntity。下面是示例代码。如果需要,请在评论中提出具体问题以进行澄清。

@RequestMapping(value = "/toggleB", method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<java.lang.String> sendCommand(@RequestBody String ident) {

// Do your stuff

return new ResponseEntity<String>("Some response data/message",new HttpHeaders(), HttpStatus.OK);
}

关于java - Spring Web 服务不会读取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23265986/

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