如何编组和取消编组HashMap <string,arraylist <string =“”>&gt; </string,>

时间:2012-09-24 09:35:01

标签: xml binding jaxb jax-ws marshalling

我有一个javabean,它有HashMap(String,ArrayList(String)) hashMap属性。 我已经生成了一个jax ws客户端。但我无法从hashMap访问ArrayList,因为它已转换为某些默认类型arraylist。我可以解决这个问题吗?

1 个答案:

答案 0 :(得分: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;
   }
}  

GenericAdaptor

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;
   }
}  

对于每种类型,您都应该拥有自己的适配器 对于String

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;