简体   繁体   中英

Adding fields to response json in spring boot get method

I have the service that gives data from repository to rest controller:

@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskRepository taskRepository;

    @Override
    public List<Task> getAllTasks() {
        return taskRepository.findAll();
    }
}

And also rest controller: @RestController @RequestMapping("/tasks") public class TaskController { @Autowired private TaskService taskService;

    @GetMapping
    public List<Task> getAllTasks() {
        return taskService.getAllTasks();
    }
}

My task is to return not only all the tasks but two fields two - todo tasks count and ready tasks count. I know how find this count from db. But what is the proper way to add this fields to response json? Response json must look like:

{
  [
    {
      "createTime": null,
      "updateTime": null,
      "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "title": "todo-task",
      "description": "blabla",
      "priority": "HIGH",
      "done": false,
    },
    {
      "createTime": null,
      "updateTime": null,
      "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "title": "done-task",
      "description": "blabla",
      "priority": "HIGH",
      "done": true,
    }
  ],
  todoCount: 1,
  doneCount: 1
}

you can do that by creating new model to be returned by the Controller and set your todoCount and doneCount values:

 @GetMapping
    public TasksModel getAllTasks() {
// get todoCount and doneCount values
          TasksModel tasksModel = new TasksModel();
          tasksModel.setTaskModelList(taskService.getAllTasks())
          tasksModel.setTodoCount(todoCount);
          tasksModel.setDoneCount(doneCount); 

        return taskModel;
    }

and TasksModel is :

class TasksModel  {
     
     List<Task> taskModelList;
     int todoCount;
     int doneCount;

//getter
//setter

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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