java中json與xml互轉
一、簡介
本文介紹java中,json串與xml串相互轉換的一種方式。
二、開發步驟
2.1 添加maven依賴
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.32</version>
</dependency>
2.2 代碼實例
import com.alibaba.fastjson.JSON;
import org.json.JSONObject;
import org.json.XML;
import java.util.HashMap;
import java.util.Map;
public class XmlJsonMain {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("k1", "v1");
map.put("k2", "v2");
//json串
String jsonStr = JSON.toJSONString(map);
System.out.println("source json : " + jsonStr);
//json轉xml
String xml = json2xml(jsonStr);
System.out.println("xml : " + xml);
//xml轉json
String targetJson = xml2json(xml);
System.out.println("target json : " + targetJson);
}
/**
* json to xml
* @param json
* @return
*/
public static String json2xml(String json) {
JSONObject jsonObj = new JSONObject(json);
return "<xml>" + XML.toString(jsonObj) + "</xml>";
}
/**
* xml to json
* @param xml
* @return
*/
public static String xml2json(String xml) {
JSONObject xmlJSONObj = XML.toJSONObject(xml.replace("<xml>", "").replace("</xml>", ""));
return xmlJSONObj.toString();
}
}
結果輸出:
source json : {"k1":"v1","k2":"v2"}
xml : <xml><k1>v1</k1><k2>v2</k2></xml>
target json : {"k1":"v1","k2":"v2"}