【问题标题】:Returning JSON Object from REST Web Service with Complex Objects从具有复杂对象的 REST Web 服务返回 JSON 对象
【发布时间】:2012-08-06 13:12:42
【问题描述】:
我公开了一个启用了 REST 的 Web 服务,它返回 RETURN_OBJ。
但是,RETURN_OBJ 本身包含几个复杂的对象,例如来自其他类、映射等的对象的 list。
在这种情况下,使用@XmlRootElement 注释参与类并使用@Produces("application/json") 注释Web 服务是否足够?
因为仅仅这样做是行不通的,我收到no message body writer found for class 错误。
这个错误的原因、原因和解决方法是什么?
【问题讨论】:
标签:
java
json
apache
rest
cxf
【解决方案1】:
@XmlRootElement
您需要使用带有 json 注释而不是 xml 注释的库。例如:杰克逊 (http://jackson.codehaus.org/)。你可以尝试使用xml writer来写json。
@Produces("application/json")
当类被json注解注解时,会返回json。
【解决方案2】:
我希望这可能会有所帮助,
以下是返回使用 Gson 构建并使用 Poster 测试的 json 对象的工作示例,并且 url 是 domainname:port//Project_name/services/rest/getjson?name=gopi
随心所欲地构造一个复杂的Object,最后使用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:我不想在 Jackson 和 Gson 之间打架 ;-)