整理了下网上能找到的常见两种xml->json的方式,主要是使用json-lib包或者org.json包进行转换最后面是现成的工具类
壹、使用json-lib方式引入依赖:
net.sf.json-lib json-lib2.4 jdk15 xom xom1.2.5
贰、使用org.json引入依赖
直接引入org.json包
org.json json20180813
或者引入hutool的包(推荐)
cn.hutool hutool-all5.7.4
叁、现成工具类
import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import net.sf.json.JSON; import net.sf.json.xml.XMLSerializer; import org.json.XML; /** * @ClassName ConvertXMLtoJSON * @Description 使用xml字符串转json的三种 * @Date 2023/11/22 10:32 * @Version 1.0 */ public class ConvertXMLtoJSON { /** 方式--壹 * 依赖json-lib实现转换 * @param xmlStr * @return */ public static String xmlToJSON1(String xmlStr){ 创建 XMLSerializer对象 XMLSerializer xmlSerializer = new XMLSerializer(); //将xml转为json(注:如果是元素的属性,会在json里的key前加一个@标识) JSON readJSON = xmlSerializer.read(xmlStr); //输出json内容 System.out.println(readJSON.toString()); return readJSON.toString(); } /** * 方式--贰 * 使用hutool工具包中的工具转化 * @param xmlStr * @return */ public static String xmlToJSON2(String xmlStr){ //这个方法转换的XML值不全为字符串 JSONObject jsonObject = JSONUtil.xmlToJson(xmlStr); System.out.println(jsonObject.toString()); //设置xml的值都以String类型显示 JSONObject jsonObject1 = cn.hutool.json.XML.toJSONObject(xmlStr, true); System.out.println(jsonObject1.toString()); return jsonObject.toString(); } /** * 方式--叁 * 使用org.json中的工具,与hutool的源码是一样的 * @param xmlStr * @return */ public static String xmlToJSON3(String xmlStr){ org.json.JSONObject jsonObject1 = XML.toJSONObject(xmlStr); org.json.JSONObject jsonObject2 = XML.toJSONObject(xmlStr,true); System.out.println(jsonObject1.toString()); System.out.println(jsonObject2.toString()); return jsonObject2.toString(); } }
肆、测试与对比
public class Demo22 { public static void main(String[] args) { String xmlStr=""; System.out.println("方式1:"+ ConvertXMLtoJSON.xmlToJSON1(xmlStr)); System.out.println("方式2:"+ ConvertXMLtoJSON.xmlToJSON2(xmlStr)); System.out.println("方式3:"+ ConvertXMLtoJSON.xmlToJSON3(xmlStr)); } } 60012000020 01 103100 MBS000253895 5295899690 20231121 110354 850812159063 9959 99959028 MBS MBS93665 67f6c99b74484c2b8bcb35473850cdd7 12312 童骄 SF 1234567890 18982714297
原xml数据(图一)、json-lib生成的json(图二)、org.json生成的json(图三)
json-lib生成的json字段是按照xml字段顺序,但去掉了最外层的标签 ;org.json解析的json包含所有的标签,包含最外层的,但没有标签顺序是乱的