Returning JSON Object from REST Web Service with Complex Objects
Solution 1
@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.
Solution 2
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 ;-)
Vicky
A software developer with zeal to learn new things all the time!!
Updated on August 26, 2020Comments
-
Vicky over 3 years
I have a rest enabled web service exposed which returns
RETURN_OBJ
.However,
RETURN_OBJ
in itself contains several complex objects likelist
of objects from other class, maps, etc.In such a case, will annotating the participating classes with
@XmlRootElement
and annotating web service with@Produces("application/json")
enough?Because just doing it is not working and I am getting
no message body writer found for class
error.What is the reason, cause and solution for this error?