Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning JSON Object from REST Web Service with Complex Objects

I have a rest enabled web service exposed which returns RETURN_OBJ.

However, RETURN_OBJ in itself contains several complex objects like list 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?

like image 516
Vicky Avatar asked Aug 09 '12 10:08

Vicky


2 Answers

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

like image 131
Gopi Shankar Avatar answered Oct 23 '22 11:10

Gopi Shankar


@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.

like image 28
Err Avatar answered Oct 23 '22 11:10

Err