当前位置: 首页 > news >正文

xml和json互转工具类

分享一个json与xml互转的工具类,非常好用

一、maven依赖

<!-->json 和 xm 互转</!--><dependency><groupId>org.dom4j</groupId><artifactId>dom4j</artifactId><version>2.1.3</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.83</version></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId></dependency>

二、工具类代码

package com.test.main;import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;import java.util.List;
import java.util.Map;
import java.util.Set;public class JsonXmlUtils {public  static JSONObject toJson(String xml){JSONObject jsonObject = new JSONObject();Document document = null;try {document = DocumentHelper.parseText(xml);} catch (DocumentException e) {e.printStackTrace();}//获取根节点元素对象Element root = document.getRootElement();return xmlToJson(root,jsonObject);}public static JSONObject  xmlToJson(Element node,JSONObject json){//获取子节点listList<Element> list = node.elements();//获取节点名字String name = node.getName();//最下面的一层if(list.isEmpty()){String nodeValue = node.getTextTrim();json.put(name, nodeValue);}else{//下级节点进行嵌套JSONObject js = new JSONObject();//判断json数据中是否存在相同的 key//存在相同的key需要使用数组存储if(json.containsKey(name)){JSONArray jsonArray = null;Object o = json.get(name);if(o instanceof JSONArray){jsonArray=(JSONArray) o;}else{jsonArray = new JSONArray();jsonArray.add(o);}json.put(name,jsonArray);jsonArray.add(js);}else {json.put(name,js);}//递归for (Element element : list) {xmlToJson(element,js);}}return json;}/*** 将json字符串转换成xml** @param json*            json字符串* @throws Exception*/public static Element toXml(String json,Element root) {JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();Element ee = jsonToXml(jsonObject, root, null);return ee.elements().get(0);}/*** 将json字符串转换成xml** @param jsonElement*            待解析json对象元素* @param parentElement*            上一层xml的dom对象* @param name*            父节点*/public static Element jsonToXml(JsonElement jsonElement, Element parentElement, String name) {if (jsonElement instanceof JsonArray) {//是json数据,需继续解析JsonArray sonJsonArray = (JsonArray)jsonElement;for (int i = 0; i < sonJsonArray.size(); i++) {JsonElement arrayElement = sonJsonArray.get(i);jsonToXml(arrayElement, parentElement, name);}}else if (jsonElement instanceof JsonObject) {//说明是一个json对象字符串,需要继续解析JsonObject sonJsonObject = (JsonObject) jsonElement;Element currentElement = null;if (name != null) {currentElement = parentElement.addElement(name);}Set<Map.Entry<String, JsonElement>> set = sonJsonObject.entrySet();for (Map.Entry<String, JsonElement> s : set) {jsonToXml(s.getValue(), currentElement != null ? currentElement : parentElement, s.getKey());}} else {//说明是一个键值对的key,可以作为节点插入了Element el = parentElement.addElement(name);el.addText(jsonElement.getAsString());}return parentElement;}}

三、实体类

这里为了更全面的演示,所以嵌套三层

第三层:

public class PeopleBase {private People people;public PeopleBase(People people) {this.people = people;}
}

第二层:

@Data
public class People {private String name;private Integer age;private List<PeopleOther> likes;
}

第三层:

@Data
public class PeopleOther {private String like;
}

四、使用方式

json转xml 

public static void main(String[] args) throws Exception {People people = new People();people.setName("张三");people.setAge(1);PeopleOther peopleOther1 = new PeopleOther();peopleOther1.setLike("冰淇淋");PeopleOther peopleOther2 = new PeopleOther();peopleOther2.setLike("巧克力");List<PeopleOther> likes = new ArrayList<>();likes.add(peopleOther1);likes.add(peopleOther2);people.setLikes(likes);// 将json转为xmlElement root = new BaseElement("root");System.out.println(JsonXmlUtils.toXml(new Gson().toJson(new PeopleBase(people)), root).asXML());}

xml转json:

public static void main(String[] args) throws Exception {String xmlStr = "<people><name>张三</name><age>1</age><likes><like>冰淇淋</like></likes><likes><like>巧克力</like></likes></people>";System.out.println(JsonXmlUtils.toJson(xmlStr));}

http://www.lryc.cn/news/146898.html

相关文章:

  • Windows系统下MMDeploy预编译包的使用
  • yolov5自定义模型训练二
  • Spring框架获取用户真实IP(注解式)
  • 利用 IDEA IDE 的轻量编辑模式快速查看和编辑工程外的文本文件
  • MyBatisx代码生成
  • 【日记】文章更新计划
  • UML用例图三种关系(重点)-架构真题(十七)
  • 分层解耦介绍
  • Nginx百科之gzip压缩、黑白名单、防盗链、零拷贝、跨域、双机热备
  • git通过fork-merge request实现多人协同
  • 元素居中的方法总结
  • 后端面试话术集锦第一篇:spring面试话术
  • elasticsearch8.9.1集群搭建
  • 前端调用电脑摄像头
  • 网络编程day1——进程间通信-socket套接字
  • Android-关于页面卡顿的排查工具与监测方案
  • VueX 与Pinia 一篇搞懂
  • 指针与空间按钮的交互
  • java八股文面试[数据库]——慢查询优化
  • 《Flink学习笔记》——第十章 容错机制
  • 【LeetCode-中等题】230. 二叉搜索树中第K小的元素
  • DQL语句的用法(MySQL)
  • 【Navicat Premium 16】使用Navicat将excel的数据进行单表的导入,详细操作
  • 学习笔记230810--vue项目中get请求的两种传参方式
  • 分享一种针对uni-app相对通用的抓包方案
  • 【2023百度之星备赛】码蹄集 BD202301 公园(BFS求最短路)
  • 2022年下半年系统架构设计师真题(下午带答案)
  • 26、ADS瞬时波形仿真-TRANSIENT仿真(以共射放大器为例)
  • 【微服务部署】02-配置管理
  • NTP时钟同步服务器