• xml和json互转工具类


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

    一、maven依赖

    1. <!-->json 和 xm 互转</!-->
    2. <dependency>
    3. <groupId>org.dom4j</groupId>
    4. <artifactId>dom4j</artifactId>
    5. <version>2.1.3</version>
    6. </dependency>
    7. <dependency>
    8. <groupId>com.alibaba</groupId>
    9. <artifactId>fastjson</artifactId>
    10. <version>1.2.83</version>
    11. </dependency>
    12. <dependency>
    13. <groupId>com.google.code.gson</groupId>
    14. <artifactId>gson</artifactId>
    15. </dependency>

    二、工具类代码

    1. package com.test.main;
    2. import com.alibaba.fastjson.JSONArray;
    3. import com.alibaba.fastjson.JSONObject;
    4. import com.google.gson.JsonArray;
    5. import com.google.gson.JsonElement;
    6. import com.google.gson.JsonObject;
    7. import com.google.gson.JsonParser;
    8. import org.dom4j.Document;
    9. import org.dom4j.DocumentException;
    10. import org.dom4j.DocumentHelper;
    11. import org.dom4j.Element;
    12. import java.util.List;
    13. import java.util.Map;
    14. import java.util.Set;
    15. public class JsonXmlUtils {
    16. public static JSONObject toJson(String xml){
    17. JSONObject jsonObject = new JSONObject();
    18. Document document = null;
    19. try {
    20. document = DocumentHelper.parseText(xml);
    21. } catch (DocumentException e) {
    22. e.printStackTrace();
    23. }
    24. //获取根节点元素对象
    25. Element root = document.getRootElement();
    26. return xmlToJson(root,jsonObject);
    27. }
    28. public static JSONObject xmlToJson(Element node,JSONObject json){
    29. //获取子节点list
    30. List<Element> list = node.elements();
    31. //获取节点名字
    32. String name = node.getName();
    33. //最下面的一层
    34. if(list.isEmpty()){
    35. String nodeValue = node.getTextTrim();
    36. json.put(name, nodeValue);
    37. }else{
    38. //下级节点进行嵌套
    39. JSONObject js = new JSONObject();
    40. //判断json数据中是否存在相同的 key
    41. //存在相同的key需要使用数组存储
    42. if(json.containsKey(name)){
    43. JSONArray jsonArray = null;
    44. Object o = json.get(name);
    45. if(o instanceof JSONArray){
    46. jsonArray=(JSONArray) o;
    47. }else{
    48. jsonArray = new JSONArray();
    49. jsonArray.add(o);
    50. }
    51. json.put(name,jsonArray);
    52. jsonArray.add(js);
    53. }else {
    54. json.put(name,js);
    55. }
    56. //递归
    57. for (Element element : list) {
    58. xmlToJson(element,js);
    59. }
    60. }
    61. return json;
    62. }
    63. /**
    64. * 将json字符串转换成xml
    65. *
    66. * @param json
    67. * json字符串
    68. * @throws Exception
    69. */
    70. public static Element toXml(String json,Element root) {
    71. JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
    72. Element ee = jsonToXml(jsonObject, root, null);
    73. return ee.elements().get(0);
    74. }
    75. /**
    76. * 将json字符串转换成xml
    77. *
    78. * @param jsonElement
    79. * 待解析json对象元素
    80. * @param parentElement
    81. * 上一层xml的dom对象
    82. * @param name
    83. * 父节点
    84. */
    85. public static Element jsonToXml(JsonElement jsonElement, Element parentElement, String name) {
    86. if (jsonElement instanceof JsonArray) {
    87. //是json数据,需继续解析
    88. JsonArray sonJsonArray = (JsonArray)jsonElement;
    89. for (int i = 0; i < sonJsonArray.size(); i++) {
    90. JsonElement arrayElement = sonJsonArray.get(i);
    91. jsonToXml(arrayElement, parentElement, name);
    92. }
    93. }else if (jsonElement instanceof JsonObject) {
    94. //说明是一个json对象字符串,需要继续解析
    95. JsonObject sonJsonObject = (JsonObject) jsonElement;
    96. Element currentElement = null;
    97. if (name != null) {
    98. currentElement = parentElement.addElement(name);
    99. }
    100. Set<Map.Entry<String, JsonElement>> set = sonJsonObject.entrySet();
    101. for (Map.Entry<String, JsonElement> s : set) {
    102. jsonToXml(s.getValue(), currentElement != null ? currentElement : parentElement, s.getKey());
    103. }
    104. } else {
    105. //说明是一个键值对的key,可以作为节点插入了
    106. Element el = parentElement.addElement(name);
    107. el.addText(jsonElement.getAsString());
    108. }
    109. return parentElement;
    110. }
    111. }

    三、实体类

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

    第三层:

    1. public class PeopleBase {
    2. private People people;
    3. public PeopleBase(People people) {
    4. this.people = people;
    5. }
    6. }

    第二层:

    1. @Data
    2. public class People {
    3. private String name;
    4. private Integer age;
    5. private List<PeopleOther> likes;
    6. }

    第三层:

    1. @Data
    2. public class PeopleOther {
    3. private String like;
    4. }

    四、使用方式

    json转xml 

    1. public static void main(String[] args) throws Exception {
    2. People people = new People();
    3. people.setName("张三");
    4. people.setAge(1);
    5. PeopleOther peopleOther1 = new PeopleOther();
    6. peopleOther1.setLike("冰淇淋");
    7. PeopleOther peopleOther2 = new PeopleOther();
    8. peopleOther2.setLike("巧克力");
    9. List<PeopleOther> likes = new ArrayList<>();
    10. likes.add(peopleOther1);
    11. likes.add(peopleOther2);
    12. people.setLikes(likes);
    13. // 将json转为xml
    14. Element root = new BaseElement("root");
    15. System.out.println(JsonXmlUtils.toXml(new Gson().toJson(new PeopleBase(people)), root).asXML());
    16. }

    xml转json

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

  • 相关阅读:
    数字孪生与GIS:智慧城市的未来之路
    WPF动画详解
    重仓比特币
    表单提交RESTful风格——GET,POST,DELETE,PUT 4种方式处理源码
    iceberg-flink 七:累积窗口使用。(CUMULATE)
    【21天学习挑战赛—经典算法】LeetCode 26. 删除有序数组中的重复项
    OpenCV自学笔记十三:图像梯度
    Vue.extend使用场景
    y92.第六章 微服务、服务网格及Envoy实战 -- Envoy基础(三)
    HarmonyOS开发:Log工具类源码分析
  • 原文地址:https://blog.csdn.net/for_the_time_begin/article/details/132583969