我在使用JSON作为JAX-RS服务时遇到问题.
下面我添加了我的代码.
这是我的服务类:
//Sets the path to base URL + /hello
@Path("/hello")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class Hello {
@GET
@Produces("application/json")
public Student getStudent() {
Student s = new Student();
s.first_name = "Test First Name !!!";
s.last_name = "Test Last Name!!!";
return s;
}
我想从服务中获得的学生班:
@XmlRootElement
public class Student implements Serializable {
public String first_name;
public String last_name;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Student()
{
first_name = "Fahad";
last_name = "Mullaji";
}
}
服务端的Web XML.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>com.vogella.jersey.first</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers under com.vogella.jersey.first package. -->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.vogella.jersey.first</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</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>
我不知道如何解决这个问题.
我正在使用SOAP UI来测试JSON响应,但我想这应该没关系.
我读过很多地方,我需要在下面添加代码.但我不知道在哪里.我没有使用Maven进行构建.
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
服务器正在寻找将Student对象解析为JSON的函数,但它无法为其找到函数或jar文件.
我已经添加了Genson,Moxy,RESTEasy和Jackson的jar,但我认为这就是问题所在.
我想我在某个地方缺少地图.
解决方法:
我能够通过安装jersey-media-json-jackson解决它
将依赖项添加到pom.xml
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<scope>runtime</scope>
</dependency>