Java Working Tools Common tool Class (iv)--json tool class, using regular support XML and JSON to switch to the "utility class"

Source: Internet
Author: User
See this topic is not most people are dismissive, indeed almost every Java program ape has written the JSON tool class, and many people have used json-lib.jar encapsulation of similar functions, but I use the regular to support the XML and JSON, reduce the introduction of the jar package. Basically meet the needs. Of course, if you need more powerful features, it's best to use json-lib to achieve it.
Take a look at the conversion JSON in the tool class and how to convert to XML. 1. XML Turn JSON

Specifically not to say, I was the use of the stupid method, many times using the replacement. A bit better is to support XML element attributes. If an XML node has attributes, it is formatted with @attributes: {Property list}. If there is only one value for the attribute, the value is formatted with @value: "Value". The code is as follows:

    /** * Formatted as JSON * * @param result * @return/public static string Fmt2json (String res
        Ult) {if (validate) {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 \": {\ "$},"). Replace ("},{", "},"). ReplaceAll ("}" ([^}|^\ "]*)}", "},\" @value \ ": \" $1\ "}");
    return JSON;
 }
2. JSON to XMLFound http://www.bejson.com/xml2json/this site using JS is simple, JS incredibly with Eval (JSON) directly into the tree object. And then it's easy to deal with. But with Java to simulate or a little difficult, I also start from the internal processing, step-by-step out of the analysis. And finally, it's simple to achieve. Of course, there are a lot of bugs. I just tested it and didn't support the conversion of the array. Have time to change it.
    /** * Formatted as XML * * @param JSON * @return/public static string Fmt2xml (String json) {
    Return Fmt2xml (JSON, "root"); /** * Formatted as XML * * @param JSON * @param rootele * @return/public static Stri
        Ng 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+ ">");
        Remove @attributes and @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 \": \\{[^}]*},? "," {\ "" +s+ "\": {");
        Matcher = Pattern.matcher (JSON);

        JSON = Json.replaceall ("\\{\" @value \ ": \" ([^\]*) \ "}", "\" $1\ "");
        Handling Nested 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;
 }
A main method to test the test bar:

    public static void Main (string[] args) {String str = "<response a=\" 123\ "b=\" 000\ ">" + "<status c=\" 123\ "d=\" 000\ ">201</status>" + "<a><s Tatus1>201</status1><message1>app is disabled by the user </message1></A> "+" ;
                                A2><status1>201</status1><message1>app disabled by user </message1></A2> " + "<B>" + "<bb><status1>201</status1><message1>app Disabled by user </message1></BB> "+" </B> "+" Message>app is disabled by the user, please lift the ban </message> "+" in the console <c><status1>201</status1

        ><message1>app is disabled by the user </message1></C> "+" </Response>; String JSON = Fmt2json (str);
        String XML = Fmt2xml (JSON);
        SYSTEM.OUT.PRINTLN ("XML transforms to JSON:" + JSON);
    SYSTEM.OUT.PRINTLN ("JSON transforms to xml:" + XML);
 }
The test results are as follows:
xml to json:{"Response": {"@attributes": {"a": "123", "B": "{"}, "status": {"@attributes": {"C": " 123 "," D ":" "@value": "201"}, "A": {"Status1": "201", "Message1": "The app is disabled by the user"}, "A2": {"Status1": "201", "Message1" : "App is disabled by user"}, "B": {"BB": {"Status1": "201", "Message1": "The app is disabled by the user"}, "message": "App is disabled by the user, please lift the ban in the console", "C": {" Status1 ":" 201 "," Message1 ":" App is disabled by the user itself "}} JSON into Xml:<?xml version=" 1.0 "? ><root><response a=" 123 "b = "><status" c= "123" d= ">201</status><A><status1>201</status1><" Message1>app is disabled by the user himself </message1></A><A2><status1>201</status1><message1> App is disabled by user </message1></A2><B><BB><status1>201</status1><message1> The app is disabled by the user itself and disabled by the user, please release the </message1></bb></b><message>app from the console </message><C>< Status1>201</status1><message1>app is disabled by the user himself </message1></c></response></root > 
You can test yourself and then go to http://www.bejson.com/index.html and http://www.bejson.com/otherformat/xml/to detect the JSON format and XML format in the results.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.