3

我有一个 XML 源,我使用 JAXB 解组对象。XML 源:

<album>
    <name>something</name>
    <id>003030</id>
    <artist>someone</artist>
    ...
</album>

Java 源代码就像(也带有所需的 getter/setter):

@XmlRootElement(name="album")
class Album {
    String name;
    Long id;
    String artist;
    ...
}

到现在为止还挺好。现在我在专辑列表中获得了一些不同大小的图片网址:

...
<image size="small">http://.../small.jpg</image>
<image size="medium">http://.../medium.jpg</image>
<image size="large">http://.../large.jpg</image>
...

我想将它映射到类似这样的java Map:

Map<String,String> imageUrls;

地图的键是大小属性,地图的值是元素值。如果可能的话,我应该如何注释这个变量?

4

1 回答 1

5

助手类 Pair

@XmlAccessorType(XmlAccessType.FIELD)
public class Pair {

    @XmlAttribute
    private String key;

    @XmlValue
    private String value;

    public Pair() {
    }

    public Pair(String key, String value) {
        this.key = key;
        this.value = value;
    }  
//... getters, setters  
}  

对列表

@XmlAccessorType(XmlAccessType.FIELD)
public class PairList 
{
    private List<Pair> values = new ArrayList<Pair>();

    public PairList() {
    }  
//...  
}  

适配器

public class MapAdaptor extends XmlAdapter<PairList, Map<String, String>> 
{
    @Override
    public Map<String, String> unmarshal(PairList list) throws Exception 
    {
        Map<String, String> retVal = new HashMap<String, String>();
        for (Pair keyValue : list.getValues()) 
        {
            retVal.put(keyValue.getKey(), keyValue.getValue());
        }
        return retVal;
    }

    @Override
    public PairList marshal(Map<String, String> map) throws Exception 
    {
        PairList retVal = new PairList();
        for (String key : map.keySet()) 
        {
            retVal.getValues().add(new Pair(key, map.get(key)));
        }
        return retVal;
    }
}

在您的实体中使用

@XmlJavaTypeAdapter(value = MapAdaptor.class)
private Map<String, String> imageUrls = new HashMap<String, String>();  

PS
你可以不用类PairList使用Pair[]而不是PairList
适配器 来做到这一点

public class MapAdaptor extends XmlAdapter<Pair[], Map<String, String>> 
{
    @Override
    public Map<String, String> unmarshal(Pair[] list) throws Exception 
    {
        Map<String, String> retVal = new HashMap<String, String>();
        for (Pair keyValue : Arrays.asList(list)) 
        {
            retVal.put(keyValue.getKey(), keyValue.getValue());
        }
        return retVal;
    }

    @Override
    public Pair[] marshal(Map<String, String> map) throws Exception 
    {
        List<Pair> retVal = new ArrayList<Pair>();
        for (String key : map.keySet()) 
        {
            retVal.add(new Pair(key, map.get(key)));
        }
        return retVal.toArray(new Pair[]{});
    }
}  

但在这种情况下,您无法控制每一对的名称。它将是项目,你不能改变它

<item key="key2">valu2</item>
<item key="key1">valu1</item>  

PS2
如果你尝试使用List<Pair>而不是PairList,你会得到Exception

ERROR: java.util.List haven't no-arg constructor
于 2012-09-05T20:36:40.303 回答