gpt4 book ai didi

java - JAXB map 适配器

转载 作者:行者123 更新时间:2023-11-30 08:53:15 25 4
gpt4 key购买 nike

我在将 XML 复杂类型转换为 java.util.Map 时遇到问题。解码时,只有值被填充,键变为 NULL。我希望将以下 XML 转换为 java.util.Map<"user_type","students">但它的到来就像java.util.Map<NULL,"students"> .有人可以告诉我为什么我得到的 key 为 NULL 吗?

XML

<root>
<myMap>
<user_type>students</user_type>
</myMap>
</root>

POJO

@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
public class MyPojo implements Serializable {

private static final long serialVersionUID = -4589166768649033266L;

@XmlElement(name = "myMap")
@XmlJavaTypeAdapter(MapAdapter.class)
private Map<String,String> myMap;

//getters and setters
}

MapAdapter 实现是 http://blog.bdoughan.com/2013/06/moxys-xmlvariablenode-using-maps-key-as.html

@Override
public Map<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
List<AdaptedEntry> adaptedEntries = adaptedMap.entries;
Map<String, String> map = new HashMap<String, String>(adaptedEntries.size());
for(AdaptedEntry adaptedEntry : adaptedEntries) {
map.put(adaptedEntry.key, adaptedEntry.value);
}
return map;
}

最佳答案

我看到的第一个错误是您使用的是 Map<String, Integer>映射,而您的 XML 具有字符串值。

按如下方式更改您的代码:

public class MapAdapter extends XmlAdapter<MapAdapter.AdaptedMap, Map<String, String>> {

public static class AdaptedMap {

@XmlVariableNode("key")
List<AdaptedEntry> entries = new ArrayList<AdaptedEntry>();

}

public static class AdaptedEntry {

@XmlTransient
public String key;

@XmlValue
public String value;

}

@Override
public AdaptedMap marshal(Map<String, String> map) throws Exception {
AdaptedMap adaptedMap = new AdaptedMap();
for(Entry<String, String> entry : map.entrySet()) {
AdaptedEntry adaptedEntry = new AdaptedEntry();
adaptedEntry.key = entry.getKey();
adaptedEntry.value = entry.getValue();
adaptedMap.entries.add(adaptedEntry);
}
return adaptedMap;
}

@Override
public Map<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
List<AdaptedEntry> adaptedEntries = adaptedMap.entries;
Map<String, String> map = new HashMap<String, String>(adaptedEntries.size());
for(AdaptedEntry adaptedEntry : adaptedEntries) {
map.put(adaptedEntry.key, adaptedEntry.value);
}
return map;
}

}

在你的MyPojo类,您需要指定需要将哪个 XML 元素映射为 Map .

@XmlElement(name = "myMap"),
@XmlJavaTypeAdapter(MapAdapter.class)
private Map<String,String> myMap;

关于java - JAXB map 适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29847343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com