我已經通過多個鏈接瞭解瞭如何在使用Jersey創建的RESTful webservice中返回JSON響應。這裏是我的代碼:Jersey JSON不適用於最新的Jersey API
的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ScraperWebProject</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.myscraper</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
MyScraper.java
package com.myscraper;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/hello")
public class MyScraper {
@GET
@Produces({MediaType.APPLICATION_JSON })
public SearchModel sayJsonHello() {
System.out.println("JSON text hello called");
SearchModel s = new SearchModel("My First Search", "My first search is done");
return s;
}
@GET
@Produces({ MediaType.TEXT_XML })
public SearchModel sayPlainTextHello() {
System.out.println("Plain text hello called");
SearchModel s = new SearchModel("My First Search", "My first search is done");
return s;
}
}
SearchModel.java
package com.myscraper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class SearchModel {
private String title;
private String description;
public SearchModel(){
}
public SearchModel(String title,String desc){
this.title = title;
this.description= desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "SearchModel [title=" + title + ", desc=" + description + "]";
}
}
我不知何故無法得到映射到該請求getJSONHello()方法。在這個Link發現的解決方案表示使用Jersey JSON,但提供的xml對於最新的Jersey版本無效。它使用com.sun關係屬性,該屬性僅對澤西島的舊版本有效。
問題被提到[此鏈接](http://stackoverflow.com/questions/29136404/severe-messagebodywriter解決 - 未發現的換媒體類型 - 應用 - JSON型級/ 29136934#29136934) –