Java 在spring boot 2中使用gson时返回null
弹簧靴2 在build.gradle中:Java 在spring boot 2中使用gson时返回null,java,spring-boot,gson,Java,Spring Boot,Gson,弹簧靴2 在build.gradle中: plugins { id 'org.springframework.boot' version '2.2.2.RELEASE' id 'io.spring.dependency-management' version '1.0.8.RELEASE' id 'war' // to use JSP } group = 'ru.otus.sd' version = '0.0.1' sourceCompatibility = '1.8'
plugins {
id 'org.springframework.boot' version '2.2.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'war' // to use JSP
}
group = 'ru.otus.sd'
version = '0.0.1'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.apache.tomcat.embed:tomcat-embed-jasper:9.0.30'
implementation 'com.google.code.gson:gson:2.7'
implementation 'javax.servlet:jstl:1.2'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
在application.yml中:
server:
port: 8090
spring:
http:
converters:
preferred-json-mapper: gson
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
这里是我的控制器:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
import java.util.List;
@RestController
public class UserController {
@GetMapping("/users")
public List<User> getAllUsers() {
return Collections.singletonList(new User() {{
setId(1);
setName("Peter");
}});
}
}
但是当尝试打开http://localhost:8090/users
我明白了
[
null
]
为什么不退回这个:
[
{
"id": 1,
"name": "Peter"
}
]
?尝试将响应对象设置为老式对象。创建新数组列表、创建新用户、设置其id、设置其名称、将其添加到列表并返回列表尝试将这些字段公开
[
{
"id": 1,
"name": "Peter"
}
]