java 最简单的xml与json相互转换

java 最简单的xml与json相互转换

绿林寻猫
2021-12-08 / 0 评论 / 190 阅读 / 正在检测是否收录...

导入依赖

        <!--xml转换-->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.9.8</version>
            <scope>compile</scope>
        </dependency>

 

 

工具类


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.util.logging.Logger;

/**
 * json对象或字符串转xml
 * @Author: LiuYong
 * @Date:2019/12/11 11:21
 * @Description: TODO json对象或字符串转xml
 */
public class JsonAndXmlUtils {
    private static Logger logger = Logger.getLogger(JsonAndXmlUtils.class.getName());


    public static void main(String[] args) throws Exception
    {
        String jsonInput = "{\"nonce_str\":\"b927722419c52622651a871d1d9ed8b2\",\"device_info\":\"1000\",\"out_trade_no\":\"1405713376\",\"appid\":\"wx2421b1c4370ec43b\",\"total_fee\":\"1\",\"sign\":\"3CA89B5870F944736C657979192E1CF4\",\"trade_type\":\"JSAPI\",\"attach\":\"att1\",\"body\":\"JSAPI支付测试\",\"mch_id\":\"10000100\",\"notify_url\":\"http://wxpay.weixin.qq.com/pub_v2/pay/notify.php\",\"spbill_create_ip\":\"127.0.0.1\"}\n";
        String jsonToXml = JsonAndXmlUtils.jsonToXml(jsonInput);
        System.out.println("jsonToXml:"+jsonToXml);
        JSONObject jsonObject = xmlToJson(jsonToXml);
        System.out.println("xmlToJson:"+jsonObject.toJSONString());
    }


    /**
     * xml字符串转json对象
     * @Author LiuYong
     * @Date 2019/12/11 11:40
     * @Description TODO xml字符串转json对象
     * @param xmlStr
     * @return JSONObject
     **/
    public static JSONObject xmlToJson(String xmlStr){
        XmlMapper xmlMapper = new XmlMapper();
        JSONObject jsonObject1=null;
        try{
            jsonObject1 = xmlMapper.readValue(xmlStr, JSONObject.class);
        }catch (Exception e){
            logger.info("ERROR com.slf.utils.utils.JsonAndXmlUtils.xmlToJson 异常:"+e.getMessage());
        }
        return jsonObject1;
    }

    /**
     * json字符串转xml字符串
     * @Author LiuYong
     * @Date 2019/12/11 11:45
     * @Description TODO json字符串转xml字符串
     * @param json
     * @return String
     **/
    public static String jsonToXml(String json){
        JSONObject jsonObject = JSONObject.parseObject(json);
        XmlMapper xmlMapper = new XmlMapper();
        String s = null;
        try{
            s = xmlMapper.writeValueAsString(jsonObject);
        }catch (Exception e){
            logger.info("ERROR com.slf.utils.utils.JsonAndXmlUtils.jsonToXml 异常:"+e.getMessage());
        }
        return s;
    }



}

 

0

评论 (0)

取消