json与xml互转

一、简介

本文介绍json串与xml串相互转换的一种方式。

二、开发步骤

1、添加maven依赖


    org.json
    json
    20171018


    com.alibaba
    fastjson
    1.2.32

2、代码实例

import com.alibaba.fastjson.JSON;
import org.json.JSONObject;
import org.json.XML;

import java.util.HashMap;
import java.util.Map;

public class XmlJsonMain {
    public static void main(String[] args) {
        Map, String> map = new HashMap<>();
        map.put("k1", "v1");
        map.put("k2", "v2");

        //json串
        String jsonStr = JSON.toJSONString(map);
        System.out.println("source json : " + jsonStr);

        //json转xml
        String xml = json2xml(jsonStr);
        System.out.println("xml  :  " + xml);
        //xml转json
        String targetJson = xml2json(xml);
        System.out.println("target json : " + targetJson);
    }

    /**
     * json to xml
     * @param json
     * @return
     */
    public static String json2xml(String json) {
        JSONObject jsonObj = new JSONObject(json);
        return "" + XML.toString(jsonObj) + "";
    }

    /**
     * xml to json
     * @param xml
     * @return
     */
    public static String xml2json(String xml) {
        JSONObject xmlJSONObj = XML.toJSONObject(xml.replace("", "").replace("", ""));
        return xmlJSONObj.toString();
    }
}

结果输出:

source json : {"k1":"v1","k2":"v2"}
xml  :  v1v2
target json : {"k1":"v1","k2":"v2"}


你可能感兴趣的:(字符串编码)