首页 > Web开发 > 详细

json串与xml串相互转换Utills

时间:2018-11-20 18:06:19      阅读:174      评论:0      收藏:0      [点我收藏+]

一 、需要添加的maven依赖

          

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.11</version>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.11</version>
</dependency>

 

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 jsonStr
* @return
*/
public static String json2xml(String jsonStr) {
JSONObject jsonObj = new JSONObject(jsonStr);
return XML.toString(jsonObj);
}

/**
* xml to json
* @param xml
* @return
*/
public static String xml2json(String xml) {


JSONObject xmlJSONObj = XML.toJSONObject(xml.replace("<xml>", "").replace("</xml>", ""));
return xmlJSONObj.toString();
}

       

        

 

json串与xml串相互转换Utills

原文:https://www.cnblogs.com/xiaokong0824/p/9990447.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!