0

I have a rest api that supports returning both XML and JSON as follows:

@GET
    @Path("/areas/city/{cityId}")
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response getAreaByCity(@PathParam("cityId") String cityId) {
        List<Area> areaList = //service call to get area
        GenericEntity<List<Area>> areaEntityList = new GenericEntity<List<Area>>(areaList) {};
        return Response.ok(areaEntityList).build();
    }

The above returns XML as default if no Accept header is defined.I want to return JSON instead..so as per the post @Produces annotation in JAX-RS, I changed my service to provide quality factor. But again XML is returned by default. After thinking for some time, I see Area class which is being used is marked with @XmlRootElement. Is this causing issue? If yes, how to resolve it? If not, how can i return JSON as default.

2
  • I am using postman rest client. However, I tested this with SOAP UI as well.. Commented Feb 18, 2015 at 9:37
  • Doing this, is returning JSON. What i want is to return JSON even if no Accept header is set. Commented Feb 18, 2015 at 9:41

1 Answer 1

3

You can try this

@POST
@Consumes({  MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response post(Student s,@HeaderParam("Accept") String accept){
    if(accept!=null && accept.contains(MediaType.APPLICATION_XML)){
    accept = MediaType.APPLICATION_XML;
    }else{
    accept = MediaType.APPLICATION_JSON;
    }
    //Construct list
    Response.ok(list, accept).build();
}
Sign up to request clarification or add additional context in comments.

8 Comments

You can check the accept type, from @HeaderParam; if the accept type is XML, we can create a Response with XML, else JSON.
Ya, for this kind of situations we need to include the checks, if the client isn't providing any accept type information, by default, XML is being sent.
@Pasupathi- that worked, but why providing the quality factor doesn't work as explained in the given link.
Quality factor also working, if you're using SOAP UI, please check the RAW tab of Response, and confirm me if you still get XML. I changed the service Produce annotation to @Produces({MediaType.APPLICATION_XML +"; qs=0.9", MediaType.APPLICATION_JSON })
Did you return an JAXB object i.e. an object marked with @XmlRootElement?
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.