我正在使用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数据。
提前感谢
发布于 2015-09-03 18:32:43
根据Jersey documentation的说法,您可以使用Moxy或JAXB将对象转换为xml文档。如果你想使用Moxy,你需要做一些进一步的配置,也就是defined here。但是,如果您想使用引用实现,请添加jaxb依赖。
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.16</version>
</dependency>首先,您必须使用适当的jaxb注释来注释您的类。这里有一个例子(不是最小的简单@XmlRootElement也可以)。
@XmlRootElement(name = "student")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "user", propOrder = {
"id",
"name",
"email"
})
public class StudentDto {
@XmlElement(name = "id", nillable = false, required = false)
private Long id;
@XmlElement(name = "name", nillable = true, required = true)
private String name;
@XmlElement(name = "email", nillable = false, required = false)
private String email;
// GETTERS && SETTERS
}然后,您必须注释您的服务,使它们既可以使用XML文档,也可以生成XML文档。例如
@Path("student")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class StudentResource {
}最后,您的客户端必须使用适当的头,以告知服务器它正在执行哪种类型的请求以及正在等待哪种类型的响应。下面是这些头文件
Content-Type: application/xml
Accept: application/xml这意味着为了运行getAllStudents服务,您需要执行类似于(update:不需要Content-Type,因为get中没有内容。感谢@peeskillet的评论)这一点。
curl -i \
-H "Accept: application/xml" \
-X GET \
http://your_endpoint:8080/your_context/your_root_path/studenthttps://stackoverflow.com/questions/32369728
复制相似问题