簡體   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