我最近遇到了一个棘手的json(我无法控制,所以我必须处理它):
{
"someOtherParam":"someValue",
"attributes":
{
"language":["fr", "en"],
"otherParam":["value1", "value2"]
}
}
attributes
是一个映射-我不知道它可能包含哪些属性,因此我不能仅将其映射到对象。我相信在Java中,我需要以某种方式{@ {1}}来映射。
我找到了very helpful post,可以让我编写这样的适配器:
Map<String,List<String>>
虽然这种通用方法适用于简单值(例如public class MapAdapter extends XmlAdapter<MapAdapter.AdaptedMap, Map<String, List<String>>> {
public static class AdaptedMap {
@XmlVariableNode("key")
List<AdaptedEntry> entries = new ArrayList<>();
}
public static class AdaptedEntry {
@XmlTransient
public String key;
@XmlValue
public List<String> value;
}
@Override
public AdaptedMap marshal(Map<String, List<String>> map) throws Exception {
AdaptedMap adaptedMap = new AdaptedMap();
for(Map.Entry<String, List<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, List<String>> unmarshal(AdaptedMap adaptedMap) throws Exception {
List<AdaptedEntry> adaptedEntries = adaptedMap.entries;
Map<String, List<String>> map = new HashMap<>(adaptedEntries.size());
for(AdaptedEntry adaptedEntry : adaptedEntries) {
map.put(adaptedEntry.key, adaptedEntry.value);
}
return map;
}
}
),但在编组中它坚持将列表映射为简单元素
Map<String,String>
那我该怎么做呢?