java實現Xml與json之間的相互轉換操作示例

這篇文章主要介紹了java實現Xml與json之間的相互轉換操作,結合實例形式分析了Java xml與json相互轉換工具類的定義與使用相關操作技巧,需要的朋友可以參考下

本文實例講述了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);
  }
}

PS:這裏再爲大家提供幾款相關在線工具供大家參考使用:

在線JSON代碼檢驗、檢驗、美化、格式化工具:
http://tools.jb51.net/code/json

在線XML/JSON互相轉換工具:
http://tools.jb51.net/code/xmljson

在線格式化XML/在線壓縮XML
http://tools.jb51.net/code/xmlformat

XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress

XML代碼在線格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat

更多關於java算法相關內容感興趣的讀者可查看本站專題:《Java操作json格式數據技巧總結》、《Java數據結構與算法教程》、《Java操作DOM節點技巧總結》、《Java文件與目錄操作技巧彙總》和《Java緩存操作技巧彙總

希望本文所述對大家java程序設計有所幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章