JAVA-JSON、XML互轉(zhuǎn)-【粗暴應(yīng)用分享】

其實(shí)很多時(shí)候,我們只需要魚,而不是漁,吶,給你魚。


在平時(shí)的開發(fā)中,有時(shí)候會(huì)用到JSON和XML的互轉(zhuǎn)

  • net.sf.json-lib.json-lib包提供一些互轉(zhuǎn)的方法;
  • com.alibaba.fastjson并沒有提供;

但是現(xiàn)在用FastJSON的人越來越多,好多人在面臨到JSON到XML互轉(zhuǎn)的時(shí)候還是有些束手無策,現(xiàn)在寫一個(gè)特別好用的工具類,分享給大家,一如既往的粗暴,好用。

1、首先,推薦你用maven,然后不用多講

<!-- https://mvnrepository.com/artifact/de.odysseus.staxon/staxon -->
        <dependency>
            <groupId>de.odysseus.staxon</groupId>
            <artifactId>staxon</artifactId>
            <version>1.3</version>
        </dependency>

這個(gè)復(fù)制粘貼丟到pom.xml文件里面,然后開始直接丟代碼:

/**
 * @ClassName StaxonUtils
 * @Description 實(shí)現(xiàn)JSON--XML互轉(zhuǎn)
 * @author watermelon_code
 * @Date 2017年7月19日 上午10:49:48
 * @version 1.0.0
 */
public class StaxonUtils {

    /**
     * @Description: json string convert to xml string
     * @author watermelon_code
     * @date 2017年7月19日 上午10:50:32
     */
    public static String json2xml(String json) {
        StringReader input = new StringReader(json);
        StringWriter output = new StringWriter();
        JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();
        try {
            XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
            XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
            writer = new PrettyXMLEventWriter(writer);
            writer.add(reader);
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return output.toString();
    }

    /**
     * @Description: json string convert to xml string ewidepay ues only
     * @author watermelon_code
     * @date 2017年7月19日 上午10:50:32
     */
    public static String json2xmlPay(String json) {
        StringReader input = new StringReader(json);
        StringWriter output = new StringWriter();
        JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();
        try {
            XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
            XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
            writer = new PrettyXMLEventWriter(writer);
            writer.add(reader);
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (output.toString().length() >= 38) {// remove <?xml version="1.0" encoding="UTF-8"?>
            return "<xml>" + output.toString().substring(39) + "</xml>";
        }
        return output.toString();
    }

    /**
     * @Description: xml string convert to json string
     * @author watermelon_code
     * @date 2017年7月19日 上午10:50:46
     */
    public static String xml2json(String xml) {
        StringReader input = new StringReader(xml);
        StringWriter output = new StringWriter();
        JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).autoPrimitive(true).prettyPrint(true).build();
        try {
            XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input);
            XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);
            writer.add(reader);
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return output.toString();
    }

    /**
     * @Description: 去掉轉(zhuǎn)換xml之后的換行和空格
     * @author watermelon_code
     * @date 2017年8月9日 下午4:05:44
     */
    public static String json2xmlReplaceBlank(String json) {
        String str = StaxonUtils.json2xml(json);
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

}

看效果吧:

public static void main(String[] args) {
        JSONObject json = new JSONObject();
        json.put("name", "jack");
        json.put("age", 25);

        String xmlstr = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[thisisatest]]></Content><MsgId>1234567890123456</MsgId></xml>";

        System.out.println("JSON-->XML:");
        System.out.println("JSON:" + json.toJSONString());
        System.out.println("---------------------------------------------------------------");
        System.out.println("普通轉(zhuǎn)XML帶格式:\n" + StaxonUtils.json2xml(json.toJSONString()));
        System.out.println("---------------------------------------------------------------");
        System.out.println("轉(zhuǎn)XML去掉頭部、前后補(bǔ)充<XML>:\n" + StaxonUtils.json2xmlPay(json.toJSONString()));
        System.out.println("---------------------------------------------------------------");
        System.out.println("普通轉(zhuǎn)XML去掉空格換行:\n" + StaxonUtils.json2xmlReplaceBlank(json.toJSONString()));
        System.out.println("---------------------------------------------------------------");
        System.out.println("XML轉(zhuǎn)JSON:\n" + StaxonUtils.xml2json(xmlstr));
    }

運(yùn)行結(jié)果:

JSON-->XML:
JSON:{"name":"jack","age":25}
---------------------------------------------------------------
普通轉(zhuǎn)XML帶格式:
<?xml version="1.0" encoding="UTF-8"?>
<name>jack</name>
<age>25</age>

---------------------------------------------------------------
轉(zhuǎn)XML去掉頭部、前后補(bǔ)充<XML>:
<xml><name>jack</name>
<age>25</age>
</xml>
---------------------------------------------------------------
普通轉(zhuǎn)XML去掉空格換行:
<?xmlversion="1.0"encoding="UTF-8"?><name>jack</name><age>25</age>
---------------------------------------------------------------
XML轉(zhuǎn)JSON:
{
    "xml" : {
        "ToUserName" : "toUser",
        "FromUserName" : "fromUser",
        "CreateTime" : 1348831860,
        "MsgType" : "text",
        "Content" : "thisisatest",
        "MsgId" : 1234567890123456
    }
}

那么這次的輪子到這里就結(jié)束了。

TO BE CONTINUE !

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,068評(píng)論 25 709
  • 溫馨提示:本文閱讀需要3分鐘,建議收藏后閱讀! 上次我們介紹了XML 今天我們來介紹 JSON 什么是JSON? ...
    Java聯(lián)盟閱讀 573評(píng)論 0 1
  • 查找目錄:find /(查找范圍) -name '查找關(guān)鍵字' -type d查找文件:find /(查找范圍) ...
    fumier閱讀 61,771評(píng)論 0 8
  • 喜歡畫畫但全是憑興趣沒受過什么專業(yè)訓(xùn)練,說白了還不是因?yàn)闆]錢哈哈,不過索性我喜歡聽著歌畫畫來打發(fā)無聊的時(shí)間,雖然畫...
    就是喜歡我自己閱讀 490評(píng)論 1 1
  • 七律/風(fēng)信子 作者:心博、圖片:網(wǎng)絡(luò) 豐滿根成大蒜頭,葉莖蔥綠碧油油。 花開攏抱春天綻,果獲團(tuán)圓夏季收。 美麗端莊...
    心博1閱讀 743評(píng)論 0 0

友情鏈接更多精彩內(nèi)容