1

I am writing a spring boot api which fetches some data from db, store in model object & returns it. But I want to return only few fields of the model as api response.

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. In response its showing all the fields. How to show only specific fields like id and age only. Selecting only id & age from db will still show all fields of model in response (name & lastname will be shown as null). Is there any way apart from creating new ModelView class or setting JsonIgnore as this model?

usr_11
  • 548
  • 10
  • 31
  • 1
    Does this [question](https://stackoverflow.com/questions/23101260/ignore-fields-from-java-object-dynamically-while-sending-as-json-from-spring-mvc) helps? `@JsonIgnore` – WoAiNii Sep 20 '20 at 17:59

1 Answers1

8

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

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. A simple example will be below (will consider MyModel from your question)

Create a class Views.java with an empty interface

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

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

Avi
  • 1,458
  • 9
  • 14