我正在使用Jersey并面临如何将复杂对象解析为xml格式的问题,请帮助我,非常感谢。 这是详细信息。
首先,我创建一个像下面这样的实体容器对象:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class RestResponse {
//It can be any kinds of type, collection, single object etc
private Object data;
//... still have many properties
public RestResponse() {
}
public RestResponse(Object data) {
this.data = data;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
这是我的实体类之一:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Entity1{
private String name;
private Map<String, Object> otherData = new HashMap<String, Object>();
public Entity1(){
this.name = "aaa";
otherData.put("address", "XXXXX");
otherData.put("age", 13);
//more...
this.otherData = otherData
}
public Entity1(String name, Integer age){
this.name = "aaa";
otherData.put("address", "XXXXX");
otherData.put("age", age);
this.otherData = otherData
}
public String getName() {
return name;
}
public Map<String, Object> getOtherData() {
return otherData;
}
}
这是我的资源类:
@Path("/test")
public class EntityResource{
@GET
@Path("test1")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response test1() {
Entity1 entity = new Entity1();
return Response.ok(new RestResponse(entity)).build();
}
@GET
@Path("test2")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response test2() {
List entities = new ArrayList<Entity1>();
entities.add(new Entity1("E1"));
entities.add(new Entity1("E2"));
return Response.ok(new RestResponse(entities)).build();
}
}
使用上面的代码配置jersey,当我需要json格式响应时它工作正常,但对于xml格式响应,我总是得到500错误,我错过了什么?
答案 0 :(得分:0)
经过一番研究,我找到了解决方案,答案很简单,我将 JacksonXMLProvider.class 注册为XML提供者,希望这可以帮助其他人。