XML和JSON互相转换

阅读更多

依赖jar包


    org.json
    json
    20171018


    com.alibaba
    fastjson
    1.2.32

 测试代码:

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 = "\n" +
                "wxe062425f740c30d8\n" +
                "10000098\n" +
                "3PG2J4ILTKCH16CQ2502SI8ZNMTM67VS\n" +
                "100000982014120919616\n" +
                "ohO4Gt7wVPxIT1A9GjFaMYMiZY1s\n" +
                "FORCE_CHECK\n" +
                "张三\n" +
                "100\n" +
                "节日快乐!\n" +
                "10.2.3.10\n" +
                "C97BDBACF37622775366F38B629F45E3\n" +
                "";
        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("", "").replace("", ""));
        String jsonStr =  xmlJSONObj.toString();
        return jsonStr;
    }

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

 

你可能感兴趣的:(xml,json,转换)