java中Xml、json之間的相互轉換


旁白:

最近關於xml與json之間的轉換都搞蒙了,這里寫一個demo,以后備用。

正題:

project格式是:

jar包是一個一個檢出來的,還算干凈了。

代碼:

工具類:

package exercise.xml;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;

import org.jdom.Document;

public class XmlExercise {

    /**
     * 將xml字符串<STRONG>轉換</STRONG>為JSON字符串
     * 
     * @param xmlString
     *            xml字符串
     * @return JSON<STRONG>對象</STRONG>
     */
    public static String xml2json(String xmlString) {
        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(xmlString);
        return json.toString(1);
    }

    /**
     * 將xmlDocument<STRONG>轉換</STRONG>為JSON<STRONG>對象</STRONG>
     * 
     * @param xmlDocument
     *            XML Document
     * @return JSON<STRONG>對象</STRONG>
     */
    public static String xml2json(Document xmlDocument) {
        return xml2json(xmlDocument.toString());
    }

    /**
     * JSON(數組)字符串<STRONG>轉換</STRONG>成XML字符串
     * 
     * @param jsonString
     * @return
     */
    public static String json2xml(String jsonString) {
        XMLSerializer xmlSerializer = new XMLSerializer();
        return xmlSerializer.write(JSONSerializer.toJSON(jsonString));
        // return xmlSerializer.write(JSONArray.fromObject(jsonString));//這種方式只支持JSON數組
    }

}

測試類:

package exercise.xml;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class XmlTest extends XmlExercise {

    public static void main(String[] args) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "horizon");
        JSONArray jsonArray = new JSONArray();
        JSONObject dataJson = new JSONObject();
        jsonArray.add(jsonObject);
        //jsonArray.add(jsonObject);
        dataJson.put("data", jsonArray);
        System.out.println(dataJson.toString());

        String xml = json2xml(dataJson.toString());
        System.out.println("xml:" + xml);
        String str = xml2json(xml);
        System.out.println("to_json" + str);

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM