java - 在 spring-boot 2 中使用 gson 时返回 null
问题描述
弹簧靴 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'
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");
}});
}
}
这里型号:
public class User {
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "\nUser{" +
"id = " + id +
", name = '" + name + '\'' +
'}';
}
}
但是当尝试打开http://localhost:8090/users
我明白了
[
null
]
为什么不返回这个:
[
{
"id": 1,
"name": "Peter"
}
]
?
解决方案
尝试使响应对象老派。创建新数组列表,创建新用户,设置其id,设置其名称,将其添加到列表并返回列表
推荐阅读
- java - 如何使用策略或功能接口处理基于值(枚举)的多项选择?
- c++ - 在 boost 中使用 what() 获取异常详细信息的替代方法
- rust - 我是否需要在 mpsc 频道上调用 close,即使我同时删除了 Sender 和 Receiver?
- vue.js - Vuejs 未知的自定义元素(导入组件错误)
- vue.js - 根据 vue.js 中的 v-if 条件显示按钮
- nginx - Nginx-rtmp vod 播放目录中的文件列表
- git - 并行检出同一存储库的不同分支
- css - 使用 scss 时是否应该使用单独的 css 扩展?
- asp.net-core - 将 .Net Core Identity 和 OIDC 与多个 .Net Core Web API 结合使用
- c# - 将 Datagridview 中的选定项目添加到列表集合