使用复杂对象从REST Web服务返回JSON对象
问题描述:
我有一个启用了休息的Web服务,它返回RETURN_OBJ
。使用复杂对象从REST Web服务返回JSON对象
然而,RETURN_OBJ
本身包含几个复杂的对象,如其他类,地图对象list
等
在这种情况下,将注释参与班级,@XmlRootElement
与@Produces("application/json")
足够的注释Web服务?
因为只是这样做不起作用,我得到no message body writer found for class
错误。
这个错误的原因,原因和解决方法是什么?
答
@XmlRootElement
您需要使用带有json注释而不是xml注释的库。例如:杰克逊(http://jackson.codehaus.org/)。您可以尝试使用xml编写器来编写json。
@Produces("application/json")
当类使用json注释注释时,将返回json。
答
我希望这可以帮助一点,
以下为恢复其使用Gson构建与Poster测试的网址是域名JSON对象的工作示例://端口项目名/服务/ REST/getjson?name = gopi
构建一个复杂的对象,只要你喜欢,最后转换为使用Gson的json。
@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:我不想给抬起头,杰克逊之间的战斗VS GSON ;-)
我希望你会搜索SO或谷歌与你的异常.. HTTP:/ /stackoverflow.com/questions/9256112/no-message-body-writer-found-json-apache-cxf-restful-webservices – Sikorski 2012-08-09 13:27:36