我在SpringBootApplication中编写了非常基本的REST服务。当我试图点击api时,我得到了Unexpected 'S'
这是我的api,
@RestController
@RequestMapping(value="/rally")
public class CreateProjectApi {
@RequestMapping(value = "/createProject",
produces = { "application/json" },
consumes = { "application/json" },
method = RequestMethod.GET)
public ResponseEntity<String> createProj() {
String s = "Success...";
return new ResponseEntity<String>(s, HttpStatus.OK);
}
}
这是我的POM.XML,
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.altimetrik.rally</groupId>
<artifactId>RallyRestApi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>RallyRestApi</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<!-- Setup Spring MVC & REST, use Embedded Tomcat -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.rallydev.rest</groupId>
<artifactId>rally-rest-api</artifactId>
<version>2.2.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
我通过标题中的content-type:application/json
通过邮递员点击api。但我得到了意想不到的“S”作为回应。我已按照此链接unexpected 's' in response of restful service但我没有得到任何解决方案。任何人都可以帮助我吗?
答案 0 :(得分:7)
正如user7790438和nbrooks的评论中所解释的那样,问题是您的回复将是纯文本(Success...
),即使您告诉它加载JSON(通过提供Content-Type: application/json
标题。
要返回JSON,您应该返回某种对象,例如,您可以创建一个ProjectStatus
类,如下所示:
public class ProjectStatus {
private String status;
public ProjectStatus(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
}
现在,在您的REST控制器中,您应该返回ResponseEntity<ProjectStatus>
,如下所示:
return new ResponseEntity<ProjectStatus>(new ProjectStatus("Success..."), HttpStatus.OK);
当您使用Postman时,这将产生以下JSON:
{"status": "Success..."}
您几乎可以返回任何您想要的对象。一个例子是在您的回复中返回创建的项目。
或者,如果您不需要JSON,则可以提供Content-Type: text/plain
标题。