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!

Creative crypter
  • 1,348
  • 6
  • 30
  • 67
  • 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 '16 at 22:03

1 Answers1

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;
}
rmlan
  • 4,387
  • 2
  • 21
  • 28
  • 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? – Creative crypter Dec 14 '16 at 22:13
  • Did you add the relevant getters and setters for DataResponse? Is [Jackson included as part of your project](http://stackoverflow.com/questions/32905917/how-to-return-json-data-from-spring-controller-using-responsebody)? – rmlan Dec 14 '16 at 22:17