简体   繁体   English

在spring boot中仅从api返回模型的特定字段

[英]Return only specific fields of model from api in spring boot

I am writing a spring boot api which fetches some data from db, store in model object & returns it.我正在编写一个 spring boot api,它从数据库中获取一些数据,存储在模型对象中并返回它。 But I want to return only few fields of the model as api response.但我只想返回模型的几个字段作为 api 响应。

List<MyModel> myModelList = new ArrayList<>();
mongoUserCollection.find().into(myModelList);



 class MyModel{
    public int id; 
    public String name;
    public String lastname;
    public int age;
// getter & setter of all properties
    }

I am showing myModelList as response.我正在显示 myModelList 作为响应。 In response its showing all the fields.作为回应,它显示了所有字段。 How to show only specific fields like id and age only.如何仅显示特定字段,例如 id 和 age 。 Selecting only id & age from db will still show all fields of model in response (name & lastname will be shown as null).仅从 db 中选择 id 和 age 仍将显示模型的所有字段作为响应(姓名和姓氏将显示为空)。 Is there any way apart from creating new ModelView class or setting JsonIgnore as this model?除了创建新的 ModelView 类或将 JsonIgnore 设置为这个模型之外,还有什么办法吗?

If the model which you are returning is going to be specific to single API go with @JsonIgnore , the below example will ignore the id in the response如果您返回的模型将特定于单个 API,请使用@JsonIgnore ,下面的示例将忽略响应中的id

class MyModel{
    @JsonIgnore
    public int id; 
    public String name;
    public String lastname;
    public int age;
}

But let say the same model is going to be used for different API and each API has different type of result then I would highly recommend @JsonView to handle those.但是假设相同的模型将用于不同的 API,并且每个 API 具有不同类型的结果,那么我强烈推荐@JsonView来处理这些。 A simple example will be below (will consider MyModel from your question)下面是一个简单的示例(将从您的问题中考虑MyModel

Create a class Views.java with an empty interface创建一个带有空接口的类Views.java

public class Views {
    public interface MyResponseViews {};
}

In Model在模型中

class MyModel{
  public int id; 
  @JsonView(Views.MyResponseViews.class)
  public String name;
  @JsonView(Views.MyResponseViews.class)
  public String lastname;
  public int age;
}

Last thing you have to add to the controller that send this response (Assuming your controller here)您必须添加到发送此响应的控制器的最后一件事(假设您的控制器在这里)

MyModelController.java我的模型控制器.java

class MyModelController {
   // Autowiring MyModelService ...

   
   @GetMapping("/get")
   @JsonView(Views.MyResponseViews.class)
   public ResponseEntity get() {
     // Your logic to return the result
   }

}

The above will return only name and lastname Refer this for more detail this上面的代码将只返回namelastname请参阅本作更详细的

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

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