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

Vic*_*cky 5 java apache rest json cxf

我有一个休息启用的Web服务暴露,返回RETURN_OBJ.

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

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

因为只是这样做不起作用,我收到no message body writer found for class错误.

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

小智 5

我希望这可能会有所帮助,
以下是返回一个json对象的工作示例,该对象使用Gson构建并使用Poster进行测试, 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";
}
Run Code Online (Sandbox Code Playgroud)

}

PS:我不想为Jackson和Gson之间的战斗提供支持;-)


Err*_*Err 2

@XmlRootElement
Run Code Online (Sandbox Code Playgroud)

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

@Produces("application/json")
Run Code Online (Sandbox Code Playgroud)

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