欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

XML和JSON互相转换

程序员文章站 2022-04-12 20:50:21
...

依赖jar包

<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>

 测试代码:

package com.vip.xfd.testtools;

import org.json.JSONObject;
import org.json.XML;
import org.junit.Test;

/**
 * Created by kenny.dong on 2018/6/2.
 */
public class XmlJsonConvertTest {

    @Test
    public void testXml2Json(){
        String xml = "<xml>\n" +
                "<mch_appid>wxe062425f740c30d8</mch_appid>\n" +
                "<mchid>10000098</mchid>\n" +
                "<nonce_str>3PG2J4ILTKCH16CQ2502SI8ZNMTM67VS</nonce_str>\n" +
                "<partner_trade_no>100000982014120919616</partner_trade_no>\n" +
                "<openid>ohO4Gt7wVPxIT1A9GjFaMYMiZY1s</openid>\n" +
                "<check_name>FORCE_CHECK</check_name>\n" +
                "<re_user_name>张三</re_user_name>\n" +
                "<amount>100</amount>\n" +
                "<desc>节日快乐!</desc>\n" +
                "<spbill_create_ip>10.2.3.10</spbill_create_ip>\n" +
                "<sign>C97BDBACF37622775366F38B629F45E3</sign>\n" +
                "</xml>";
        String jsonStr = xml2json(xml);
        System.out.println(jsonStr);

    }

    @Test
    public void testJson2xml(){
        String jsonStr = "{\"nonce_str\":\"3PG2J4ILTKCH16CQ2502SI8ZNMTM67VS\",\"re_user_name\":\"张三\",\"amount\":100,\"mchid\":10000098,\"partner_trade_no\":\"100000982014120919616\",\"openid\":\"ohO4Gt7wVPxIT1A9GjFaMYMiZY1s\",\"mch_appid\":\"wxe062425f740c30d8\",\"sign\":\"C97BDBACF37622775366F38B629F45E3\",\"check_name\":\"FORCE_CHECK\",\"spbill_create_ip\":\"10.2.3.10\",\"desc\":\"节日快乐!\"}";
        String xmlStr = json2xml(jsonStr);
        System.out.println(xmlStr);
    }

    private String xml2json(String xml){
        JSONObject xmlJSONObj = XML.toJSONObject(xml.replace("<xml>", "").replace("</xml>", ""));
        String jsonStr =  xmlJSONObj.toString();
        return jsonStr;
    }

    private String json2xml(String json){
        JSONObject jsonObj = new JSONObject(json);
        return "<xml>" + XML.toString(jsonObj) + "</xml>";
    }
}

 

相关标签: xml json 转换