java中使用XStream實現將對象轉為xml格式字串或者將xml格式的字串轉換為對象==

來源:互聯網
上載者:User

java中使用XStream實現將對象轉為xml格式字串或者將xml格式的字串轉換為對象==

我們經常會有需求,比如調用別人的介面,別人會返回給你json或者xml格式的資料,然後我們要轉換為相應的對象供我們自己使用;
也有的時候是別人的調我們的介面,讓我們提供xml格式的資料或者json格式的資料,json的話這裡都不說了,很好處理,甚至springMvc本身就很容易支援。
下面只介紹xml和對象彼此轉換

首先我們需要引入的jar包:xstream-1.4.8.jar

下面直接貼代碼,代碼是在springMvc環境下寫的

@Controllerpublic class NavigationAppDataController extends BaseController{    @SuppressWarnings("unused")    private static final Logger     log = LoggerFactory.getLogger(NavigationAppDataController.class);    @Autowired    private StoNavigationAppManager stoNavigationAppManager;    @RequestMapping(value = "/appsite/getNavigationXmlData.htm")    public void getNavigationXmlData(HttpServletRequest request,HttpServletResponse response){        List findStoreNavigationAppToXml = stoNavigationAppManager.findStoreNavigationAppData();        XStreamConfig xStreamConfig = new XStreamConfig();        // 這裡是什麼意思我下面文字中會介紹,大概就是對xml中節點進行重新命名的        xStreamConfig.getAliasMap().put("topcategories", List.class);        xStreamConfig.getAliasMap().put("category", NavigationAppCommand.class);        String xml = toXML(findStoreNavigationAppToXml, xStreamConfig);        // 設定返回資料的編碼格式        response.setCharacterEncoding(CharsetType.UTF8);        // 設定內容類型,決定瀏覽器將以什麼類型讀我們返回的資料進行展示        response.setContentType("application/xml");        // 將資料寫入response返回給請求端        response.getWriter().write(xml);    }    /**     * 將bean對象根據xStreamConfig格式轉成xml格式的字串返回     *      * @param bean     *            對象     * @param xStreamConfig     *            配置     * @return     */    public static String toXML(Object bean,XStreamConfig xStreamConfig){        XStream xstream = constructXStream(xStreamConfig);        return xstream.toXML(bean);    }    /**     * 將xml字串轉為相對應的對象     *      * @param xml     * @return     */    public static  T fromXML(String xml){        return fromXML(xml, null);    }    public static  T fromXML(String xml,XStreamConfig xStreamConfig){        XStream xstream = constructXStream(xStreamConfig);        return (T) xstream.fromXML(xml);    }    public static XStream constructXStream(XStreamConfig xStreamConfig){        XStream xstream = new XStream();        if (Validator.isNotNullOrEmpty(xStreamConfig)){            // *******************alias********************************************            Map> aliasMap = xStreamConfig.getAliasMap();            if (Validator.isNotNullOrEmpty(aliasMap)){                for (Map.Entry> entry : aliasMap.entrySet()){                    String key = entry.getKey();                    Class value = entry.getValue();                    // 類重新命名                    xstream.alias(key, value);                }            }            // *******************implicitCollectionMap********************************************            Map> implicitCollectionMap = xStreamConfig.getImplicitCollectionMap();            if (Validator.isNotNullOrEmpty(implicitCollectionMap)){                for (Map.Entry> entry : implicitCollectionMap.entrySet()){                    String key = entry.getKey();                    Class value = entry.getValue();                    xstream.addImplicitCollection(value, key);                }            }        }    }}
/** * XStream相關配置. * */public final class XStreamConfig{    /** 別名. */    private Map> aliasMap              = new HashMap>();    /** 隱式集合 隱藏,隱藏,比如下面有list,泛型中的第二個參數 Class 是 ownerType. */    private Map> implicitCollectionMap = new HashMap>();    /**     * 獲得 別名.     *     * @return the aliasMap     */    public Map> getAliasMap(){        return aliasMap;    }    /**     * 設定 別名.     *     * @param aliasMap     *            the aliasMap to set     */    public void setAliasMap(Map> aliasMap){        this.aliasMap = aliasMap;    }    /**     * 獲得 隱式集合 隱藏,隱藏,比如下面有list,泛型中的第二個參數 Class 是 ownerType.     *     * @return the implicitCollectionMap     */    public Map> getImplicitCollectionMap(){        return implicitCollectionMap;    }    /**     * 設定 隱式集合 隱藏,隱藏,比如下面有list,泛型中的第二個參數 Class 是 ownerType.     *     * @param implicitCollectionMap     *            the implicitCollectionMap to set     */    public void setImplicitCollectionMap(Map> implicitCollectionMap){        this.implicitCollectionMap = implicitCollectionMap;    }}

實現方法很簡單另外這裡說一下response的幾個參數設定的意思。

response.setCharacterEncoding(CharsetType.UTF8);
設定返回資料的編碼格式如果不設定這個,返回到客戶請求端的資料可能會亂碼,這個編碼格式一定要統一掉

response.setContentType(“application/xml”);
設定內容類型,決定瀏覽器將以什麼類型讀我們返回的資料進行展示,如果不設定,那麼瀏覽器顯示的就是一大坨xml格式的字串,沒有任何效果,而設定之後就可以像我上面的那樣,節點可以點擊展開和關閉,並且資料和節點顏色對比明顯,便於觀看。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.