I have a javabean which have HashMap (String, ArrayList(String) ) hashMap attribute. i have generated a jax ws client . But i am not able to access ArrayList from hashMap as it has converted to some default type arraylist.How can I solve this problem?
问问题
596 次
1 回答
1
使用附加类Pair
@XmlAccessorType(XmlAccessType.FIELD)
public class Pair
{
private String key;
private String[] value;
public Pair()
{
}
public Pair(String key, String[] value)
{
this.key = key;
this.value = value;
}
}
和XmlJavaAdaptor
public class PairAdaptor extends XmlAdapter<Pair[], HashMap<String, ArrayList<String>>>
{
@Override
public HashMap<String, ArrayList<String>> unmarshal(Pair[] v) throws Exception
{
final HashMap<String, ArrayList<String>> retVal = new HashMap<String, ArrayList<String>>();
for (Pair pair : v)
{
retVal.put(pair.key, new ArrayList<String>(Arrays.asList(pair.value)));
}
return retVal;
}
@Override
public Pair[] marshal(HashMap<String, ArrayList<String>> v) throws Exception
{
final Pair[] retVal = new Pair[v.size()];
int counter = 0;
for (String key : v.keySet())
{
retVal[counter] = new Pair(key, v.get(key).toArray(new String[]{}));
counter++;
}
return retVal;
}
}
用法
@XmlJavaTypeAdapter(PairAdaptor.class)
private HashMap<String, ArrayList<String>> value;
更新。泛型而不是字符串
对
@XmlAccessorType(XmlAccessType.FIELD)
public class Pair<T>
{
private String key;
private T[] value;
public Pair()
{
}
public Pair(String key, T[] value)
{
this.key = key;
this.value = value;
}
public String getKey()
{
return key;
}
public T[] getValue()
{
return value;
}
}
通用适配器
public class GenericAdaptor<T> extends XmlAdapter<Pair[], HashMap<String, ArrayList<T>>>
{
@Override
public HashMap<String, ArrayList<T>> unmarshal(Pair[] v) throws Exception
{
final HashMap<String, ArrayList<T>> retVal = new HashMap<String, ArrayList<T>>();
for (Pair<T> pair : v)
{
retVal.put(pair.getKey(), new ArrayList<T>(Arrays.asList(pair.getValue())));
}
return retVal;
}
@Override
public Pair[] marshal(HashMap<String, ArrayList<T>> v) throws Exception
{
final Pair[] retVal = new Pair[v.size()];
int counter = 0;
for (String key : v.keySet())
{
retVal[counter] = new Pair(key, v.get(key).toArray());
counter++;
}
return retVal;
}
}
对于每种类型,您都应该有自己的适配器。
对于字符串
public class StringAdaptor extends GenericAdaptor<String>
{
}
对于猫
public class CatAdaptor extends GenericAdaptor<Cat>
{
}
用法
@XmlJavaTypeAdapter(StringAdaptor.class)
private HashMap<String, ArrayList<String>> value;
@XmlJavaTypeAdapter(CatAdaptor.class)
private HashMap<String, ArrayList<Cat>> cats;
于 2012-09-24T11:07:07.540 回答