【问题标题】:spring boot with restcontroller using jsonobject not working使用jsonobject的带有restcontroller的spring boot不起作用
【发布时间】:2018-05-12 07:45:00
【问题描述】:

我使用的是spring boot,如果我使用jsonobject类型请求,则在制作restcontroller或controller时它不起作用,而当我将类型更改为string时同样有效。

@Controller
@RequestMapping("rest/dummy")

public class CustomerController {

    @GetMapping("test")
    public ResponseEntity test(@RequestParam("req") JSONObject inputData) {
        org.json.JSONObject response = new org.json.JSONObject();
        response.put("abc", "123");
        return new ResponseEntity(inputData.toString(), HttpStatus.OK);
    }

pom.xml:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.8.RELEASE</version>
</dependency>
<dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20171018</version>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0.2</version>
        </dependency>

我确实想同时使用 GET 和 POST 类型,并且我想将 jsonobject 用于请求和响应,因为数据可以随时更改及其类型。

【问题讨论】:

标签: spring-boot


【解决方案1】:

在 RequestParam 中,我们发送在 URL 中添加的键值, 要发送 Json 对象,请在 RequestBody 中发送。

使用 @RequestBody 并在请求的正文部分发送您的 Json。

【讨论】:

  • 我也想使用 GET 类型,那样的话我必须在 URL 中传递它
  • RequestParam 始终为 string ,在您的方法中将该字符串转换为 Json 对象,使用 Jackson json 解析器。
  • 不,它不起作用,但我注意到相同的应用程序在 linux 上运行良好,而在 windows 上却不行。在 Linux 中,它使用 RequestParam 作为 JSONObject
【解决方案2】:

使用真正的 POJO 作为参数和返回值是 imo 更好的方法。使用 Jackson 注释来配置这些 POJO。

无论如何。这应该有效:

@GetMapping("test")
public ResponseEntity<String> test(@RequestParam("req") JSONObject inputData) {
    org.json.JSONObject response = new org.json.JSONObject();
    response.put("abc", "123");
    return ResponseEntity.ok(inputData.toString());
}

或者

@GetMapping("test")
public ResponseEntity<SomeOutputDto> test(@RequestParam("req") String inputData) {

    SomeOutputDto out = new SomeOutputDto();
    out.setAbc(123);
    return ResponseEntity.ok(dto);
}

这需要一个额外的类:SomeOutputDto,但另一方面,您可以更好地控制您的代码。

public class SomeOutputDto {
   private int abc = 0;

  public void setAbc(int v) {
    this.abc = v;
  }
  public int getAbc() { return this.abc; }
}

【讨论】:

  • 试过但没用,我也想使用json,因为我有可以不断变化的请求,并且没有POJO的刚性结构
【解决方案3】:

使用 apache-tomcat 8.0.15 可以正常工作,同样不能使用 apache-tomcat 8.0.49

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-15
    • 2022-01-04
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2020-07-11
    • 2021-07-31
    • 2020-10-02
    相关资源
    最近更新 更多