java json与xml互转工具类

部分代码参考:https://blog.csdn.net/CDWLX/article/details/119038509
工具类

public class XmlMutualConversionJsonUtil {


    /**
     * 测试的main方法
     */
    public static void main(String[] args) throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<root>"
                + " <mdcardno>查询卡号</mdcardno>"
                + " <count>返回明细条数</count>"
                + " <rd1>"
                + " <test>"
                + "     <trxzone>交易地区号1</trxzone>"
                + "     <trxcurr>交易币种1</trxcurr>"
                + " </test>"
                + " </rd1>"
                + " <rd>"
                + "     <trxzone>交易地区号2</trxzone>"
                + "     <trxcurr>交易币种2</trxcurr>"
                + " </rd>"
                + " <rd>"
                + "     <trxzone>交易地区号3</trxzone>"
                + "     <trxcurr>交易币种3</trxcurr>"
                + "</rd>"
                + "</root>";
        JSONObject jsonObject =toJson(xml);
        System.out.println(jsonObject);
        System.out.println("----------------");
        Element root=new BaseElement("root");
        Element element = toXml(jsonObject.toJSONString(), root);
        System.out.println(element.asXML());
    }

    public  static  JSONObject  toJson(String xml){
        JSONObject jsonObject = new JSONObject();
        Document document = null;
        try {
            document = DocumentHelper.parseText(xml);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //获取根节点元素对象
        Element root = document.getRootElement();
        return xmlToJson(root,jsonObject);
    }

    public static JSONObject  xmlToJson(Element node,JSONObject json){
        //获取子节点list
        List<Element> list = node.elements();
        //获取节点名字
        String name = node.getName();
        //最下面的一层
        if(list.isEmpty()){
            String nodeValue = node.getTextTrim();
            json.put(name, nodeValue);
        }else{
            //下级节点进行嵌套
            JSONObject js = new JSONObject();
            //判断json数据中是否存在相同的 key
            //存在相同的key需要使用数组存储
            if(json.containsKey(name)){
                JSONArray jsonArray = null;
                Object o = json.get(name);
                if(o instanceof JSONArray){
                    jsonArray=(JSONArray) o;
                }else{
                    jsonArray = new JSONArray();
                    jsonArray.add(o);
                }
                json.put(name,jsonArray);
                jsonArray.add(js);
            }else {
                json.put(name,js);
            }
            //递归
            for (Element element : list) {
                xmlToJson(element,js);
            }

        }
        return json;
    }

    /**
     * 将json字符串转换成xml
     *
     * @param json
     *            json字符串
     * @throws Exception
     */
    public static Element toXml(String json,Element root) {
        JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
        Element ee = jsonToXml(jsonObject, root, null);
        return ee.elements().get(0);
    }

    /**
     * 将json字符串转换成xml
     *
     * @param jsonElement
     *            待解析json对象元素
     * @param parentElement
     *            上一层xml的dom对象
     * @param name
     *            父节点
     */
    public static Element jsonToXml(JsonElement jsonElement, Element parentElement, String name) {
        if (jsonElement instanceof JsonArray) {
            //是json数据,需继续解析
            JsonArray sonJsonArray = (JsonArray)jsonElement;
            for (int i = 0; i < sonJsonArray.size(); i++) {
                JsonElement arrayElement = sonJsonArray.get(i);
                jsonToXml(arrayElement, parentElement, name);
            }
        }else if (jsonElement instanceof JsonObject) {
            //说明是一个json对象字符串,需要继续解析
            JsonObject sonJsonObject = (JsonObject) jsonElement;
            Element currentElement = null;
            if (name != null) {
                currentElement = parentElement.addElement(name);
            }
            Set<Map.Entry<String, JsonElement>> set = sonJsonObject.entrySet();
            for (Map.Entry<String, JsonElement> s : set) {
                jsonToXml(s.getValue(), currentElement != null ? currentElement : parentElement, s.getKey());
            }
        } else {
            //说明是一个键值对的key,可以作为节点插入了
            Element el = parentElement.addElement(name);
            el.addText(jsonElement.getAsString());
        }
        return parentElement;
    }

}

依赖 jar包

  <dependency>
            <groupId>org.dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>2.1.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,可以使用dom4j和fastjson库来实现XMLJSON的功能。具体步骤如下: 1.使用dom4j解析XML文件,将其换为Document对象。 ```java SAXReader reader = new SAXReader(); Document document = reader.read(new File("example.xml")); ``` 2.使用XPath表达式选择需要换的节点,并将其换为JSON对象。 ```java JSONObject jsonObject = new JSONObject(); Element root = document.getRootElement(); List<Element> elements = root.selectNodes("//book"); for (Element element : elements) { JSONObject bookObject = new JSONObject(); bookObject.put("id", element.attributeValue("id")); bookObject.put("name", element.elementText("name")); bookObject.put("author", element.elementText("author")); bookObject.put("price", element.elementText("price")); jsonObject.put(element.attributeValue("id"), bookObject); } ``` 3.使用fastjsonJSON对象换为JSON字符串。 ```java String jsonString = JSON.toJSONString(jsonObject); ``` 完整代码如下: ```java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.File; import java.util.List; public class XmlToJsonUtil { public static String xmlToJson(String xmlFilePath) throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read(new File(xmlFilePath)); JSONObject jsonObject = new JSONObject(); Element root = document.getRootElement(); List<Element> elements = root.selectNodes("//book"); for (Element element : elements) { JSONObject bookObject = new JSONObject(); bookObject.put("id", element.attributeValue("id")); bookObject.put("name", element.elementText("name")); bookObject.put("author", element.elementText("author")); bookObject.put("price", element.elementText("price")); jsonObject.put(element.attributeValue("id"), bookObject); } return JSON.toJSONString(jsonObject); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值