tzanuttini
tzanuttini

Reputation: 25

How to return a string in response that have @Produces(MediaType.APPLICATION_JSON)?

@GET
@Path("/paises/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response findCountryList(@PathParam("id")int id){
    try{
    ArrayList<Country> lista = new ArrayList<>();
    for(int i=0; i<10 ;i++){
        Country c = new Country();
        c.setId(i);
        c.setName("country"+i);
        c.setCode("countryIsoCode"+i);
        c.setRegion("region"+i);
        lista.add(c);
        }
    
    Country co = lista.stream().filter(x -> x.getId()==id).findAny().get();
    if(id > lista.size()-1) throw new Exception("That id is not correct");
    return Response.ok(co).build();
    }catch(Exception e){
        
        return Response.status(404).entity(e.getMessage()).build();
        }
    }

I want to return a json when I don't have an Exception but when i have it I need to return a string with the exception message but this drop error of json parse.

Upvotes: 2

Views: 4546

Answers (3)

Alex McAllister
Alex McAllister

Reputation: 181

From the sample code you provided and the tags for this question, you are probably better off using an Exception handler rather than catching and returning a hand-crafted message, and letting your @GET method return your domain object. The JAX-RS library (Jersey in this case?) will serialize it to JSON since your method is annotated with APPLICATION_JSON.

https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-en/cn/part1/chapter7/exception_handling.html

For Jersey specifically: https://howtodoinjava.com/jersey/jax-rs-jersey-custom-exceptions-handling-with-exceptionmapper/

Upvotes: 0

cassiomolin
cassiomolin

Reputation: 131067

A single quoted string is a valid JSON. So you could use:

return Response.status(404).entity("\"" + e.getMessage() + "\"").build();

However I advise you to return a JSON object instead. It gives you the flexibility to return extra metadata about the error.

You could use a Map<String, Object>:

Map<String, Object> errorDetails = new HashMap<>();
errorDetails.put("message", e.getMessage());
return Response.status(404).entity(errorDetails).build();

Or create a class for the error details:

public class ErrorDetails {

    private String message;

    ...
}
ErrorDetails errorDetails = new ErrorDetails;
errorDetails.setMessage(e.getMessage());
return Response.status(404).entity(errorDetails).build();

For reporting problems in an HTTP API, have a look at the RFC 7807.

Upvotes: 2

chandrakant
chandrakant

Reputation: 370

why are you not interested to use WILDCARD expression like,

 @Path("getSupportEmail/{broadcastMprId}")
    @GET
    @Produces(MediaType.MEDIA_TYPE_WILDCARD)
    public Response getSupportEmailByBroadcastMprId(@PathParam("broadcastMprId") Integer broadcastMprId) {
        return Response.ok(broadcastMprBean.getSupportEmailByBroadcastMprId(broadcastMprId)).build();
    }

Upvotes: 0

Related Questions