[英]Marshall/Unmarshall Map
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class ItemSubstitutionRequestDTO { public ItemSubstitutionRequestDTO() { } private List<Map<String,Integer>> substituteFor=new ArrayList<Map<String,Integer>>(); private String orderId; public List<Map<String,Integer>> getSubstituteFor() { return substituteFor; } public void setSubstituteFor(List<Map<String,Integer>> substituteFor) { this.substituteFor = substituteFor; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } }
最終結果錯誤:
java.util.Map 是一個接口,JAXB 不能處理接口。
我無法讓 JaxB 能夠編組/解組 Map 的實例。我也嘗試了其他注釋,發現這是解決上述錯誤的可能方法之一,但沒有任何效果。
下面是來自 UI 端的輸入 json
{ "itemSubstitutionRequestDTO": { "substituteFor": [{"41712":2}], "orderId": "1073901", } }
您沒有編寫<substituteFor>
元素中的 XML 內容的外觀。 因此,我假設是這樣的:
<itemSubstitutionRequestDTO>
<substituteFor>
<item>
<key>x</key>
<value>23</value>
</item>
<item>
<key>y</key>
<value>3</value>
</item>
</substituteFor>
<orderId>abc</orderId>
</itemSubstitutionRequestDTO>
正如 JAXB 錯誤消息已經告訴您的那樣,它無法處理具有< >
之間的接口的類型,例如您的List<Map<String,Integer>>
。 但是,它可以處理具有< >
之間的普通類的類型,例如List<SubstitutionMap>
。
因此,第一步是重寫您的ItemSubstitutionRequestDTO
類,使其不使用List<Map<String,Integer>>
,而是使用List<SubstitutionMap>
。 您需要自己編寫SubstitutionMap
類(不是接口)。 但它可以非常簡單:
public class SubstitutionMap extends HashMap<String, Integer> {
}
現在 JAXB 不再拋出錯誤,但它仍然不知道如何編組/解組SubstitutionMap
。 因此,您需要為它編寫一個XmlAdapter
。 我們稱之為SubstitutionMapAdapter
。 為了使JAXB知道這個適配器,你需要注釋substituteFor
財產在你ItemSubstitutionRequestDTO
與類:
@XmlJavaTypeAdapter(SubstitutionMapAdapter.class)
適配器的工作是進行從SubstitutionMap
到SubstitutionMapElement
數組的實際轉換,反之亦然。 然后 JAXB 可以自己處理SubstitutionMapElement
數組。
public class SubstitutionMapAdapter extends XmlAdapter<SubstitutionMapElement[], SubstitutionMap> {
@Override
public SubstitutionMap unmarshal(SubstitutionMapElement[] elements) {
if (elements == null)
return null;
SubstitutionMap map = new SubstitutionMap();
for (SubstitutionMapElement element : elements)
map.put(element.getKey(), element.getValue());
return map;
}
@Override
public SubstitutionMapElement[] marshal(SubstitutionMap map) {
// ... (left to you as exercise)
}
}
SubstitutionMapElement
類只是一個鍵和值的簡單容器。
@XmlAccessorType(XmlAccessType.FIELD)
public class SubstitutionMapElement {
private String key;
private int value;
// ... constructors, getters, setters omitted here for brevity
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.