我有一个输出 POJO 列表的 REST 服务。响应 XML/JSON 包含使用 XMLElement 注释的所有字段。有没有办法限制响应中的字段(在运行时以编程方式)?我也可以在运行时再次指定字段的顺序吗?
POJO:
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Employee {
@XmlElement
@Column(name="Name", length=75) @NotNull @Length(max=75)
private String name;
@XmlElement
@Column(name="designation", length=75)
private String designation;
@XmlElement
@Column(name="department", length=75)
private String department;
}
@Path("employee")
public class EmployeeRestService {
@GET
@Path("json")
@Produces(MediaType.APPLICATION_JSON)
public Response emp() {
return Response.ok(getDetails(), MediaType.APPLICATION_JSON).build();;
}
@Path("xml")
@Produces(MediaType.APPLICATION_XML)
public Response emp() {
GenericEntity<List<Employee>> list = new GenericEntity<List<Employee>>(getDetails()) {};
return Response.ok(list, MediaType.APPLICATION_XML).build();;
}
public List<Employee> getDetails() {
.....
return list;
}
}
My output now is:
JSON:
[{name:Tom,designation:Manager,department:IT},{name:Jim,designation:Clerk,department:IT}]
XML:
<employees>
<employee>
<name>Tom</name>
<designation>Manager</designation>
<department>IT</department>
</employee>
<employee>
<name>Jim</name>
<designation>Clerk</designation>
<department>IT</department>
</employee>
</employees>
Desired output:
JSON:
[{designation:Manager,name:Tom},{designation:Clerk,name:Jim}]
XML:
<employees>
<employee>
<designation>Manager</designation>
<name>Tom</name>
</employee>
<employee>
<designation>Clerk</designation>
<name>Jim</name>
</employee>
</employees>
只有在提交请求时才知道字段和顺序。所以像 JSONIgnore 这样的注释对我没有帮助。我该怎么做?我试过金森。虽然我可以限制 JSON 响应中的字段,但我无法对 XML 响应执行此操作。我也无法订购这些字段。