[java] Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

In controller I create json array. If I return List<JSONObject> it is ok:

@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List<JSONObject> getAll() {
    List<Entity> entityList = entityManager.findAll();

    List<JSONObject> entities = new ArrayList<JSONObject>();
    for (Entity n : entityList) {
        JSONObject entity = new JSONObject();
        entity.put("id", n.getId());
        entity.put("address", n.getAddress());
        entities.add(entity);
    }
    return entities;
}

but I need to return JSON array and HTTP status code:

@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<List<JSONObject>> getAll() {
    List<Entity> entityList = entityManager.findAll();

    List<JSONObject> entities = new ArrayList<JSONObject>();
    for (Entity n : entityList) {
        JSONObject Entity = new JSONObject();
        entity.put("id", n.getId());
        entity.put("address", n.getAddress());
        entities.add(entity);
    }
    return new ResponseEntity<JSONObject>(entities, HttpStatus.OK); // XXX
}

Eclipse see error in XXX line:

Multiple markers at this line
    - The constructor ResponseEntity<JSONObject>(List<JSONObject>, HttpStatus) is undefined
    - Type mismatch: cannot convert from ResponseEntity<JSONObject> to 
     ResponseEntity<List<JSONObject>>
    - Type mismatch: cannot convert from ResponseEntity<JSONObject> to JSONObject

How can I return json+http reply? There is my working code for returning one json object + http status code:

@RequestMapping(value="/{address}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<JSONObject> getEntity(@PathVariable("address") int address) {
    Entity n = entityManager.findByAddress(address);
    JSONObject o = new JSONObject();
    o.put("id", n.getId());
    o.put("address", n.getAddress());
    return new ResponseEntity<JSONObject>(o, HttpStatus.OK);
}

This question is related to java json spring rest http-status-codes

The answer is


Now I return Object. I don't know better solution, but it works.

@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<Object> getAll() {
    List<Entity> entityList = entityManager.findAll();

    List<JSONObject> entities = new ArrayList<JSONObject>();
    for (Entity n : entityList) {
        JSONObject Entity = new JSONObject();
        entity.put("id", n.getId());
        entity.put("address", n.getAddress());
        entities.add(entity);
    }
    return new ResponseEntity<Object>(entities, HttpStatus.OK);
}

I am late for this but i want put some more solution relevant to this.

 @GetMapping
public ResponseEntity<List<JSONObject>> getRole() {
    return ResponseEntity.ok(service.getRole());
}

I have no idea why the other answers didn't work for me (error 500) but this works

@GetMapping("")
public String getAll() {
    List<Entity> entityList = entityManager.findAll();
    List<JSONObject> entities = new ArrayList<JSONObject>();
    for (Entity n : entityList) {
        JSONObject Entity = new JSONObject();
        entity.put("id", n.getId());
        entity.put("address", n.getAddress());
        entities.add(entity);
    }
    return entities.toString();
}

Instead of

return new ResponseEntity<JSONObject>(entities, HttpStatus.OK);

try

return new ResponseEntity<List<JSONObject>>(entities, HttpStatus.OK);

Personally, I prefer changing the method signature to:

public ResponseEntity<?>

This gives the advantage of possibly returning an error message as single item for services which, when ok, return a list of items.

When returning I don't use any type (which is unused in this case anyway):

return new ResponseEntity<>(entities, HttpStatus.OK);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to http-status-codes

Laravel - Return json along with http status code Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>" HTTP status code 0 - Error Domain=NSURLErrorDomain? 400 vs 422 response to POST of data Python Request Post with param data HTTP Get with 204 No Content: Is that normal Throw HttpResponseException or return Request.CreateErrorResponse? Returning http status code from Web Api controller How to specify HTTP error code? How to get HTTP response code for a URL in Java?