Returning JSON Object from REST Web Service with Complex Objects
I hope this might help a bit,
Following is an working example for returning a json object which was constructed using Gson and tested with Poster and the url is domainname:port//Project_name/services/rest/getjson?name=gopi
Construct a complex Object as you like and finally convert to json using Gson.
@Path("rest")public class RestImpl {@GET@Path("getjson")@Produces("application/json")public String restJson(@QueryParam("name") String name){ EmployeeList employeeList = new EmployeeList(); List<Employee> list = new ArrayList<Employee>(); Employee e = new Employee(); e.setName(name); e.setCode("1234"); Address address = new Address(); address.setAddress("some Address"); e.setAddress(address); list.add(e); Employee e1 = new Employee(); e1.setName("shankar"); e1.setCode("54564"); Address address1 = new Address(); address.setAddress("Address "); e1.setAddress(address); list.add(e1); employeeList.setEmplList(list); Gson gson = new Gson(); System.out.println(gson.toJson(employeeList)); return gson.toJson(employeeList);}@GET@Produces("text/html")public String test(){ return "SUCCESS";}
}
PS: I dont want to give heads up for fight between Jackson vs Gson ;-)
@XmlRootElement
You need to use a libary with json annotations instead of xml annotations. ex: jackson (http://jackson.codehaus.org/). You can try to use a xml writer to write json.
@Produces("application/json")
When the classes are annotated with the json annotations, json will be returned.