繁体   English   中英

从具有复杂对象的REST Web服务返回JSON对象

[英]Returning JSON Object from REST Web Service with Complex Objects

我有一个休息启用的Web服务公开,返回RETURN_OBJ

但是, RETURN_OBJ本身包含几个复杂的对象,如来自其他类,地图等的对象list

在这种情况下,是否会使用@XmlRootElement注释参与类并使用@Produces("application/json")注释Web服务?

因为只是这样做不起作用,我no message body writer found for class错误的no message body writer found for class编写器。

这个错误的原因,原因和解决方案是什么?

我希望这可能会有所帮助,
下面是一个返回一个json对象的工作示例,该对象使用Gson构建并使用Poster进行测试,url是

根据需要构造一个复杂的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之间的战斗提供支持;-)

@XmlRootElement

您需要使用带有json注释的库而不是xml注释。 例如:杰克逊( http://jackson.codehaus.org/ )。 您可以尝试使用xml编写器来编写json。

@Produces("application/json")

当使用json注释对类进行注释时,将返回json。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM