-2

First, thank you very much for reading this question.

I have a JPA project and everything works fine, the json that i get with the controller is of this form:

{"id": 1, "name": "Canada"},{"id": 2, "name": "USA"}

All its fine but i would like to get a json with the Jsend standard, it something like this:

{
status : "success",
data : {
    "country" : [
        {"id": 1, "name": "Canada"},
        {"id": 2, "name": "USA"}
    ]
  }
}

{
  "status" : "fail",
  "data" : { "title" : "A title is required" }
}

{
 "status" : "error",
 "message" : "Unable to communicate with database"
}

As you can see i want to have a status that says success, fail or error: But i dont know how to do it. This is my DTO, DAO and Controller

@Entity
public class Country implements Serializable {

private static final long serialVersionUID = -7256468460105939L;

@Id
@Column(name="id")
private int id;

@Column(name="name")
private String name;

//Constructor, get and set 

DAO

@Repository
@Transactional
public class CountryRepository {

  @PersistenceContext
  EntityManager entityManager;

  public CountryDTO findById(int id) {
      return entityManager.find(CountryDTO.class, id);
  }
}

Controller

@RestController
public class CountryController {

    @Autowired
    CountryDTO repository;

    @RequestMapping(value="api/country/{id}", method=RequestMethod.GET)
    public @ResponseBody CountryDTO getByID(@PathVariable("id") int id){
        return repository.findById(id);
    }
}

Again thank you for your time.

George
  • 7
  • 4

1 Answers1

-1

Its very good question from my point of view. So I can give list of action items to achieve this.

  1. You should aware of @ControllerAdvice annotation which is available in Spring.
  2. By utilizing that you can play with your response object.
  3. Then You should create your own Object which is similar to JSend. In my case, I have created JSendMessage class

    public class JSendMessage {
        String status;
        String message;
        Object data;
        // Add getter and setter
    }
    
  4. Now you should map above class with your @ControllerAdvice return your required object.

  5. So whenever there is a exception you can create and send your own custom exception message. There will be lot of reference for this. Just look for @ControllerAdvice
Satz
  • 307
  • 3
  • 19