0

I have a basic Rest Controller which returns a list of models in json to the client:

@RestController
public class DataControllerREST {

    @Autowired
    private DataService dataService;

    @GetMapping("/data")
    public List<Data> getData() {
        return dataService.list();
    }

}

Which returns data in this format:

[

    {
        "id": 1,
        "name": "data 1",
        "description": "description 1",
        "active": true,
        "img": "path/to/img"
    },
    // etc ...

]

Thats great for starting, but i thought about returning data of this format:

[
    "success": true,
    "count": 12,
    "data": [
        {
            "id": 1,
            "name": "data 1",
            "description": "description 1",
            "active": true,
            "img": "path/to/img"
        },
        {
            "id": 2,
            "name": "data 2",
            "description": "description 2",
            "active": true,
            "img": "path/to/img"
        },
    ]
    // etc ...

]

But i am not sure about this issue as i can not return any class as JSON... anybody has suggestions or advices?

Greetings and thanks!

1
  • When your JSON starts with "[", that means its an array. Did you actually mean an array or did you mean an object ({}) with an array of data in it?
    – Adam
    Dec 14, 2016 at 22:03

1 Answer 1

7

"as i can not return any class as JSON" - says who?

In fact, that's exactly what you should do. In this case, you will want to create an outer class that contains all of the fields that you want. It would look something like this:

public class DataResponse {

    private Boolean success;
    private Integer count;
    private List<Data> data;

    <relevant getters and setters>
}

And your service code would change to something like this:

@GetMapping("/data")
public DataResponse getData() {
    List<Data> results = dataService.list();
    DataResponse response = new DataResponse ();
    response.setSuccess(true);
    response.setCount(results.size());
    response.setData(results);
    return response;
}
2
  • hey, thanks for answer, i ment the "converter" which was complaining: " org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type: class com.example.app.rest.controller.DataResponse " do you have any suggestions? Dec 14, 2016 at 22:13
  • Did you add the relevant getters and setters for DataResponse? Is Jackson included as part of your project?
    – rmlan
    Dec 14, 2016 at 22:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.