【发布时间】:2017-11-14 15:31:47
【问题描述】:
我在 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。但我得到了 Unexpected 'S' 作为回应。我已经关注了这个链接unexpected 's' in response of restful service,但我没有从中得到任何解决方案。谁能帮我解决这个问题?
【问题讨论】:
-
那是因为您的响应不是 JSON 格式并且您指定您将生成 JSON,错误意味着它应该是 { 签名,因为它 iexpected JSON but he found S character
-
如何以 JSON 格式做出响应? @user7790438
-
@Nithyananth 您的响应需要是一个对象或一个集合/数组,然后由 Spring 在类路径中找到的转换器序列化。如果您真的只是希望您的回复是文本
Success...,那么这不是 JSON,您可以将您的回复类型更改为"text/plain"。此外,由于您的服务不接受任何参数,因此您实际上并不需要RequestMapping中的consumes参数。 -
我想返回
"JSON",所以你能给出示例代码应该是怎样的吗? @nbrooks -
要么删除生产元素,要么将响应媒体类型设为 JSON。
标签: java json rest maven spring-boot