簡體   English   中英

使用Jersey解析XML中的復雜對象

[英]Parse a Complex Object in XML with Jersey

我正在使用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錯誤,我錯過了什么?

經過一番研究,我找到了解決方案,答案很簡單,我將JacksonXMLProvider.class注冊為XML提供者,希望這可以幫助其他人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM