import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
/**
* 依赖jar包
* Maven地址
* https://mvnrepository.com/artifact/cn.hutool/hutool-all
* <dependency>
* <groupId>cn.hutool</groupId>
* <artifactId>hutool-all</artifactId>
* <version>5.8.3</version>
* </dependency>
*
* Maven地址
* https://mvnrepository.com/artifact/com.alibaba/fastjson
* <dependency>
* <groupId>com.alibaba</groupId>
* <artifactId>fastjson</artifactId>
* <version>1.2.68</version>
* <scope>compile</scope>
* </dependency>
*/
public class XmlJsonUtil {
public static void main(String[] args) {
// XML转JSON
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<bookstore>\n" +
" <book category=\"COOKING\">\n" +
" <title lang=\"en\">Everyday Italian</title>\n" +
" <author>Giada De Laurentiis</author>\n" +
" <year>2005</year>\n" +
" <price>30.00</price>\n" +
" </book>\n" +
" <book category=\"CHILDREN\">\n" +
" <title lang=\"en\">Harry Potter</title>\n" +
" <author>J K. Rowling</author>\n" +
" <year>2005</year>\n" +
" <price>29.99</price>\n" +
" </book>\n" +
" <book category=\"WEB\">\n" +
" <title lang=\"en\">XQuery Kick Start</title>\n" +
" <author>James McGovern</author>\n" +
" <author>Per Bothner</author>\n" +
" <author>Kurt Cagle</author>\n" +
" <author>James Linn</author>\n" +
" <author>Vaidyanathan Nagarajan</author>\n" +
" <year>2003</year>\n" +
" <price>49.99</price>\n" +
" </book>\n" +
"</bookstore>";
//把Xml转成jsonObject
JSONObject jsonObject = xmlToJson(xml);
System.out.println(jsonObject.toString());
System.out.println("------------------------------------");
//把jsonObject转成xml
String xmlData = jsonToXml(jsonObject);
System.out.println(xmlData);
}
/**
* 把xml转成JSONObject
*
* @param xml xml数据
* @return 转换后的JSONObject数据
*/
public static JSONObject xmlToJson(String xml) {
//去除xml开头和结尾的双引号
StringBuilder sb = new StringBuilder();
sb.append(xml);
if (sb.charAt(0) == '\"') {
sb.deleteCharAt(0);
}
if (sb.charAt(sb.length() - 1) == '\"') {
sb.deleteCharAt(sb.length() - 1);
}
Map<String, Object> stringObjectMap = XmlUtil.xmlToMap(sb.toString());
String json = JSONObject.toJSONString(stringObjectMap);
return JSONObject.parseObject(json, JSONObject.class);
}
/**
* 把JSONObject转成xml
*
* @param json JSONObject数据
* @return 转换后的xml
*/
public static String jsonToXml(JSONObject json) {
Map tmpMap = json.toJavaObject(Map.class);
return XmlUtil.mapToXmlStr(tmpMap);
}
}
Java xml和json互相转换
最新推荐文章于 2024-04-15 16:27:41 发布