我正在使用 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数据。
提前致谢
最佳答案
根据Jersey documentation ,您可以使用 Moxy 或 JAXB RI 将对象转换为 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 文档。例如
@Path("student")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class StudentResource {
}
最后,您的客户端必须使用正确的 header ,告诉服务器它正在执行什么样的请求以及它正在等待什么样的响应。这是这些标题
Content-Type: application/xml
Accept: application/xml
这意味着为了运行 getAllStudents 服务,您需要执行类似的操作(更新:不需要 Content-Type,因为 get 中没有内容。感谢 @peeskillet 的评论)。
curl -i \
-H "Accept: application/xml" \
-X GET \
http://your_endpoint:8080/your_context/your_root_path/student
关于java - 如何解决使用 jersey 在 java Rest 服务中生成 xml 的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32369728/