Question

I'm using jax-rs to make API in grails. I would like it to only use JSON and no XML at all. So when I replace

@Produces(['application/xml','application/json'])

with just

@Produces(['application/json'])

it helps and all successful responses are returned as JSON. Only problem is that whenever there is a DomainObjectNotFoundException it still uses XML format. I've been trying to find how to change that one also but unsuccessful so far.

So for example:

throw new DomainObjectNotFoundException(User.class, dto.id)

still responds with xml response

<error>User with id iva not found</error>

and I would like to get JSON response.

Thank you in advance

Was it helpful?

Solution

According to this code, it looks like the XML content-type is being hardcoded in the construction of the exception. To me, you have two options in this case

  1. Create your own exception for this same purpose (most elegant, but possibly overkill)
  2. Do the following (a lot less elegant, but easy):

     def exception = new DomainObjectNotFoundException(User.class, dto.id)
     def response = Response.fromResponse(exception.response).type(MediaType.APPLICATION_JSON)
     throw new WebApplicationException (newResponse)
    

    Note that you will no longer be throwing a specific DomainObjectNotFoundException, so this may not be the best option for you. After writing that out, I would honestly just go with option 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top