有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在springboot 2中使用gson时,java返回null

弹簧靴2

内置。格雷德尔:

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()
}

正在申请中。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"
  }
]

?


共 (0) 个答案