java中json与xml互转

java中json与xml互转

一、简介

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

二、开发步骤

2.1 添加maven依赖

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

2.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, 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>" + XML.toString(jsonObj) + "</xml>";
    }

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

结果输出:

source json : {"k1":"v1","k2":"v2"}
xml  :  <xml><k1>v1</k1><k2>v2</k2></xml>
target json : {"k1":"v1","k2":"v2"}
发布了274 篇原创文章 · 获赞 95 · 访问量 50万+

猜你喜欢

转载自blog.csdn.net/chinabestchina/article/details/105212055