【发布时间】:2015-09-03 07:41:44
【问题描述】:
我正在使用 jersey 创建简单的 Web 服务。
这里一切正常,但我无法以 xml 格式获取数据现在我使用 json 格式显示此 json 显示器的数据我添加了 jersey-media-moxy 依赖项,我不知道我需要添加任何xml依赖。
这是我的 pom.xml
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<!-- uncomment this to get JSON support -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<dependency>
<groupId>net.vz.mongodb.jackson</groupId>
<artifactId>mongo-jackson-mapper</artifactId>
<version>1.4.2</version>
</dependency>
</dependencies>
这是我的资源
@Path("student")
public class StudentResource {
private static Map<Integer, Students> stud_data = new HashMap<Integer, Students>();
static{
for(int i = 0; i < 10; i++){
Students stu = new Students();
int id = i+1;
stu.setId(id);
stu.setName("My Student "+id);
stu.setAge(new Random().nextInt(15)+1);
stud_data.put(id, stu);
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Students> getall(){
return new ArrayList<Students>(stud_data.values());
}
}
请帮帮我,我怎样才能显示像json这样的xml数据。
提前致谢
【问题讨论】:
-
@Produces(MediaType.APPLICATION_XML)?您可以拥有多种媒体类型,只需将它们添加在{.., ..}之间,用逗号分隔即可。您还需要确保将请求上的Accept标头设置为您想要的类型。 -
我只给@Produces(MediaType.APPLICATION_XML),但显示错误消息HTTP Status 500 - Internal Server Error
-
添加these ExceptionMapper 之一。但是使用泛型类型
Exception,即ExceptionMapper<Exception>。我的猜测是这是一个抛出的 JAXB 异常,它没有被异常映射器处理。只需在映射器中打印堆栈跟踪。如果您看到堆栈跟踪,请发布它。 -
还要确保
Student类使用@XmlRootElement注释
标签: java json xml web-services jersey