当前位置:首页 » JavaScript技术

XML和JSON互相转换

2018-06-03 08:20 本站整理 浏览(11)

依赖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>";
    }
}