简体   繁体   English

在 spring-boot 2 中使用 gson 时返回 null

[英]return null when use gson in spring-boot 2

Spring Boot 2弹簧靴 2

in build.gradle:在 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()
}

in application.yml:在 application.yml 中:

server:
  port: 8090

spring:
  http:
    converters:
      preferred-json-mapper: gson
  mvc:
    view:
      prefix: /WEB-INF/jsp/
      suffix: .jsp

here my controller:这是我的控制器:

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");
        }});
    }
}

Here model:这里模型:

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 + '\'' +
                '}';
    }
}

But when try to open http://localhost:8090/users但是当尝试打开http://localhost:8090/users

I get我得到

[
  null
]

Why not return this:为什么不返回这个:

[
  {
    "id": 1,
    "name": "Peter"
  }
]

? ?

Try to make the response object old-school.尝试使响应对象变得老式。 Create new array list, create new User, set its id, set its name, add it to the list and return the list创建新数组列表,创建新用户,设置其id,设置其名称,将其添加到列表中并返回列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM