java - Spring Boot REST API - 显示信息的问题

标签 java spring rest spring-mvc

我已关注this tutorial使用 Spring Boot 构建 REST API。我已经让它运行并响应我的调用,但它显示的信息有问题。当我要求输入时,我希望看到类似的内容

{
"id": 1,
"name": "petName",
"photo": "meh",
"status": "Meh"
},

但是我得到了

{
"id": 1,
"photo": "meh",
"status": "Meh"
},

我完全不知道为什么。

休息 Controller

@RestController
@RequestMapping("/pet")
class PetRestController {

private final PetRepo petRepo;

@RequestMapping(value="/{petId}", method = RequestMethod.GET)
Pet getPet(@PathVariable Long petId) {
    return this.petRepo.findOne(petId);
}

@RequestMapping(value="/all", method = RequestMethod.GET)
List<Pet> getPets() {
    return this.petRepo.findAll();
}

@RequestMapping(value="/delete/{petId}", method = RequestMethod.DELETE)
void deletePet(@PathVariable Long petId) {
    this.petRepo.delete(petId);
}

@RequestMapping(value="/add", method = RequestMethod.POST)
void addPet(@RequestParam String name, @RequestParam String photo, @RequestParam String status) {
    Pet pet = new Pet(name, photo, status);
    this.petRepo.save(pet);
}

@Autowired
PetRestController(PetRepo petRepo){
    this.petRepo = petRepo;
}
}

Pet.java

@Entity
public class Pet {

@Id
@GeneratedValue
private Long id;

public Long getId() {
    return id;
}

public String getName() {
    return name;
}

public String getPhoto() {
    return photo;
}

public String getStatus() {
    return status;
}

@JsonIgnore
public String name;
public String photo;
public String status;

public Pet(String name, String photo, String status) {
    this.name = name;
    this.photo = photo;
    this.status = status;
}

Pet() {

}
}

大家有什么想法吗?

最佳答案

您有一个注释告诉 Spring 不要name 序列化为 JSON。删除注释,

// @JsonIgnore // <-- remove this.
public String name;

关于java - Spring Boot REST API - 显示信息的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37364204/

相关文章:

java - if 语句中的 sendKey 问题

java swing 按住两个鼠标按钮

java - 在 Android 中实现 View.OnClickListener 的最佳方式

java - 在每个 @Test 范围之间请求新的单例 bean "WebDriver"

REST API 缓存,我应该使用反向代理还是 memcache(d)?

java - 在 Java 中创建时如何正确锁定资源

java - Spring MVC 文件名编码错误

rest - 如果内容协商失败,正确的后备措施是什么?

c# - 如何在 ASP.Net Core MVC 模型中使用 C# 解析来自 REST API 的 json 数据并将其显示在 HTML 页面上

spring - @RequestMapping 中前斜杠的处理