5

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?

Nishant
  • 54,584
  • 13
  • 112
  • 127
Vicky
  • 16,679
  • 54
  • 139
  • 232
  • i hope you would have searched SO or Google with your exception .. http://stackoverflow.com/questions/9256112/no-message-body-writer-found-json-apache-cxf-restful-webservices – Sikorski Aug 09 '12 at 13:27

2 Answers2

5

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

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

Francis Upton IV
  • 19,322
  • 3
  • 53
  • 57
Err
  • 291
  • 2
  • 13