0

I want to add JSON message on REST controller class(methods). For example i have delete method look's like:

@DeleteMapping("/people/{id}")
    public ResponseEntity<PersonDto> deletePerson(@PathVariable Long id) {
        return personService
                .deletePerson(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

I want to return message Person (maybe numer of id) deleted. Should i use ExceptionHandler? Or Can i do this Using exceptionHnadler?

1 Answers1

0

Define a ResponseBean POJO class as

public class ResponseBean {

    public final Long id;
    public final String msg;

    public ResponseBean(Long id, String msg) {
        this.id = id;
        this.msg = msg;
    }

    public Long getId() {
        return id;
    }

    public String getMsg() {
        return msg;
    }
}

Change your controller method as

@DeleteMapping("/people/{id}")
public ResponseEntity<ResponseBean> deletePerson(@PathVariable Long id) {
    return personService
            .deletePerson(id)
            .map(dto -> new ResponseBean(dto.getId(), "Person Deleted Successfully"))
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
}

Response

{
  "id" : 2,
  "msg" : "Person Deleted Successfully"
}

You can customize ResponseBean class as per your need.

Hemant Patel
  • 3,160
  • 1
  • 20
  • 29
  • I have springbootproject. Should i have create pojo class and call bean, or should i create bean in configuration springboot class? – Magdalena Rumakowicz May 10 '18 at 09:23
  • You just need to create a POJO class (similar to `PersonDto`), no need to create in `configuration`. Also you can choose any other name you like instead of `ResponseBean` – Hemant Patel May 10 '18 at 10:18