Java工作利器之常用工具類(四)——Json工具類,使用正則支援xml與json互轉__【工具 + 生產力類】

來源:互聯網
上載者:User
看到這個題目是不是大部分人都不屑一顧,的確基本上每個java程式猿都寫過json工具類,也有很多人都使用json-lib.jar封裝過類似的功能,但是我這裡使用了正則來支援xml與json的互轉,減少了jar包的引入。基本上滿足了需求。當然如果你需要更強大的功能,還是最好使用json-lib來實現。
主要看一下工具類中的轉換json和轉換成xml的方法吧。 1. xml轉json

具體就不多說了,我是採用的笨方法,多次使用正則進行替換的。比較好的一點兒是支援xml元素屬性。如果xml節點有屬性會使用 @attributes:{屬性列表} 進行格式化處理。如果有屬性只有一個值,那值要採用@value:"值"進行格式化。代碼如下:

    /**     * 格式化為json格式     *      * @param result     * @return     */    public static String fmt2Json(String result){        if(validate(result)){            return result;        }        result = result.replaceAll(">\\s*<", "><").replaceAll("<\\?([^>|^\\?]*)\\?>", "");        String json = result;        Matcher matcher = Pattern.compile("<([^>|^/]*)>").matcher(result);        while(matcher.find()){            for (int i = 0; i < matcher.groupCount(); i++) {                String s = matcher.group(i+1);                json = json.replaceAll("<"+s+">([^<|^\"]*)</"+s+">", "\""+s+"\":\"$1\",");            }        }        json = "{"+json.replaceAll(",?</([^<]*)>", "},").replaceAll("<([^<]*)>", "\"$1\":{")+"}";        json =json.replaceAll(",}","}").replaceAll("(\\s*\\w*)=\"(\\w*)\"\\s*\"?", "\"$1\":\"$2\",")                .replaceAll("\\s+([^{]*),:" ,  ":{\"@attributes\":{\"$1},").replace("},{", "},")                .replaceAll("},([^}|^\"]*)}", "},\"@value\":\"$1\"}");        return json;    }
2. json轉xml 發現http://www.bejson.com/xml2json/這個網站採用js比較簡單,js居然用eval(json)就直接轉化為樹形對象了。然後就處理簡單了。但是用java來類比還是有點困難,本人也是從內部開始處理,一步一步的往外解析。然後最終簡單實現了。當然還是有許多bug吧。剛測試了一下,居然不支援數組的轉換。有時間再改改吧。
    /**     * 格式化為xml格式     *      * @param json     * @return     */    public static String fmt2Xml(String json){        return fmt2Xml(json, "root");    }    /**     * 格式化為xml格式     *      * @param json     * @param rootEle     * @return     */    public static String fmt2Xml(String json, String rootEle){        if(!validate(json)){            return fmt2Xml(fmt2Json(json),rootEle);        }        rootEle = rootEle.replaceAll("\\W", "");        rootEle = StringsUtil.isNullOrEmpty(rootEle)? "root": rootEle;//        return json.replaceAll("\"(\\w*)\":\"?([^\",}]*)\"?,?","<$1>$2</$1>").replaceAll("\\{([^\\}]*)\\}", "<?xml version=\"1.0\" encoding=\"utf-8\" ?><"+rootEle+">$1"+"</"+rootEle+">");        //去掉@attributes和@value        Pattern pattern = Pattern.compile("\"@attributes\":\\{([^}]*)}");        Matcher matcher = pattern.matcher(json);        int t =0;        while(matcher.find()){            t++;            String s = "";            for (int i = 0; i < matcher.groupCount(); i++) {                s = matcher.group(i+1);                s = s.replaceAll("\"(\\w*)\":\"([^\"]*)\",?", " $1=$2");            }            json = json.replaceAll("[^,]\"(\\w*)\":\\{\"@attributes\":\\{[^}]*},?","{\"$1"+s+"\":{");            //matcher = pattern.matcher(json);        }        json = json.replaceAll("\\{\"@value\":\"([^\"]*)\"}", "\"$1\"");        //處理嵌套        json = json.replaceAll("\"([\\w|\\s|=]*)\":\"([^\",{}]+)\",?", "<$1>$2</$1>");        pattern = Pattern.compile("\"(\\w*)\":\\{([^{}]*)},?");        while(pattern.matcher(json).find()){            json = pattern.matcher(json).replaceAll("<$1>$2</$1>");        }        pattern = Pattern.compile("\"([\\w|\\s|=]*)\":([^}\"]*)},?");        while(pattern.matcher(json).find()){            json = pattern.matcher(json).replaceAll("<$1>$2</$1>");        }        json = json.replaceAll("(\\w*)=(\\w*)", "$1=\"$2\"").replaceAll("/(\\w*)\\s[\\w*)=\"\\w*\"\\s?]*", "/$1").replaceAll("[{|}]", "");        json = "<?xml version=\"1.0\" ?><"+rootEle+">"+json+"</"+rootEle+">";        return json;    }
來一個main方法測試測試吧:

    public static void main(String[] args) {        String str = "<Response a=\"123\" b=\"000\">"                                + "<status  c=\"123\" d=\"000\">201</status>"                                + "<A><status1>201</status1><message1>APP被使用者自己禁用</message1></A>"                                + "<A2><status1>201</status1><message1>APP被使用者自己禁用</message1></A2>"                                + "<B>"                                + "    <BB><status1>201</status1><message1>APP被使用者自己禁用</message1></BB>"                                + "</B>"                                + "<message>APP被使用者自己禁用,請在控制台解禁</message>"                                + "<C><status1>201</status1><message1>APP被使用者自己禁用</message1></C>"                            + "</Response>";        String json = fmt2Json(str);        String xml = fmt2Xml(json);        System.out.println("xml轉化為json:" + json);        System.out.println("json轉化為xml:" + xml);    }
測試結果如下:
xml轉化為json:{"Response":{"@attributes":{"a":"123","b":"000"},"status":{"@attributes":{"c":"123","d":"000"},"@value":"201"},"A":{"status1":"201","message1":"APP被使用者自己禁用"},"A2":{"status1":"201","message1":"APP被使用者自己禁用"},"B":{"BB":{"status1":"201","message1":"APP被使用者自己禁用"}},"message":"APP被使用者自己禁用,請在控制台解禁","C":{"status1":"201","message1":"APP被使用者自己禁用"}}}json轉化為xml:<?xml version="1.0" ?><root><Response a="123" b="000"><status c="123" d="000">201</status><A><status1>201</status1><message1>APP被使用者自己禁用</message1></A><A2><status1>201</status1><message1>APP被使用者自己禁用</message1></A2><B><BB><status1>201</status1><message1>APP被使用者自己禁用</message1></BB></B><message>APP被使用者自己禁用,請在控制台解禁</message><C><status1>201</status1><message1>APP被使用者自己禁用</message1></C></Response></root>
可以自行測試,然後到http://www.bejson.com/index.html 和 http://www.bejson.com/otherformat/xml/ 來檢測結果中的json格式和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.