Java作業利器の常用ツールクラス(四)——Jsonツールクラス、正則を使用してxmlとjsonの相互回転をサポートする

7688 ワード

このテーマを見ると、ほとんどの人が顧みないのではないでしょうか.確かに基本的にjavaプログラム猿ごとにjsonツール類を書いたことがありますが、json-libを使っている人も多いです.jarは類似の機能をカプセル化したことがあるが,ここではxmlとjsonの相互回転をサポートするために正則を用い,jarパケットの導入を低減した.基本的に需要を満たした.もちろん、より強力な機能が必要な場合は、json-libを使用して実現したほうがいいです.
主にツールクラスのjson変換とxml変換の方法を見てみましょう.
1.xml回転json
具体的にはあまり言わないが、私は愚かな方法を採用して、何度も正則を使って置き換えた.xml要素のプロパティをサポートするのが良いです.xmlノードに属性がある場合は@attributes:{属性リスト}を使用してフォーマット処理を行います.属性が1つしかない場合は、@value:[値](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でシミュレーションするのは少し難しいですが、本人も内部から処理し、一歩一歩外に解析しています.そして最終的には簡単に実現した.もちろんバグはたくさんあるでしょう.テストしたばかりなのに、配列の変換はサポートされていません.時間があればまた直しましょう.
    /**
     *     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形式を検出します.