WebService處理Map

遇到cxf本身不能處理的數據,如cxf不能本身處理Map對象,遇到這種狀況須要開發工程師本身寫代碼處理
1.@XmlJavaTypeAdapter:該註解修飾不能處理的類型,該註解jDK自帶的,經過value指定一個轉換器:
        //@XmlJavaTypeAdapter:該註解jDK自帶的,經過value指定一個轉換器
	@XmlJavaTypeAdapter(value=FKXMLAdapter.class)Map<String, Cat> getAllCats();
	FKXMLAdapter類是咱們本身定義的.
	Map<String, Cat>是cxf不能處理的類型.
	
2.FKXMLAdapter的代碼以下
        FKXMLAdapter繼承XmlAdapter,用StringCat模擬Map<String, Cat>
       /**
 * @author xp
 * @Title: FKXMLAdapter.java
 * @Package com.xp.cn.ws.adapter
 * @Description: TODO
 * @date 2016年5月1日 下午5:56:56
 * @version V1.0  
 */
package com.xp.cn.ws.adapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.annotation.adapters.XmlAdapter;

import com.xp.cn.bean.Cat;
import com.xp.cn.bean.StringCat;
import com.xp.cn.bean.StringCat.Entry;

/**
 * @author xp
 * @ClassName: FKXMLAdapter
 * @Description: TODO
 * @date 2016年5月1日 下午5:56:56
 * ValueType:能解決的類型  自定義爲StringCat
 * BoundType:不能解決的類型  Map<String, Cat>
 * 實現集成的方法達到StringCat,Map<String, Cat>之間的相互轉換
 */
public class FKXMLAdapter extends XmlAdapter<StringCat, Map<String, Cat>> 
{

	@Override
	public Map<String, Cat> unmarshal(StringCat v) throws Exception 
	{
		Map<String, Cat> map = new HashMap<String, Cat>();
		for (Entry entry : v.getEntries()) 
		{
			System.out.println(entry.getKey());
			map.put(entry.getKey(), entry.getValue());
		}
		return map;
	}

	@Override
	public StringCat marshal(Map<String, Cat> v) throws Exception 
	{
		StringCat stringcat = new StringCat();
		for (String key : v.keySet()) 
		{
			stringcat.getEntries().add(new Entry("", v.get(key)));
		}
		return stringcat;
	}

}
        
3.StringCat的代碼以下:
    /**
 * @author xp
 * @Title: StringCat.java
 * @Package com.xp.cn.ws.bean
 * @Description: TODO
 * @date 2016年5月1日 下午5:59:48
 * @version V1.0  
 */
package com.xp.cn.bean;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xp
 * @ClassName: StringCat
 * @Description: TODO
 * @date 2016年5月1日 下午5:59:48
 * Entry封裝了Map信息
 */

public class StringCat 
{
	public static class Entry
	{
		private String key;
		private Cat value;
		
		public Entry() {
		}

		public Entry(String key, Cat value) {
			this.key = key;
			this.value = value;
		}

		public String getKey() 
		{
			return key;
		}
		
		public void setKey(String key) 
		{
			this.key = key;
		}
		
		public Cat getValue() 
		{
			return value;
		}
		
		public void setValue(Cat value) 
		{
			this.value = value;
		}
	}
	
	private List<Entry> entries = new ArrayList<Entry>();

	public List<Entry> getEntries() 
	{
		return entries;
	}

	public void setEntries(List<Entry> entries) 
	{
		this.entries = entries;
	}
	
}
相關文章
相關標籤/搜索