Anand
Anand

Reputation: 21310

XML returns as default instead of JSON rest service

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.

Upvotes: 0

Views: 4913

Answers (1)

Pasupathi Rajamanickam
Pasupathi Rajamanickam

Reputation: 2052

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();
}

Upvotes: 3

Related Questions