当前位置:网站首页>Jackson XML is directly converted to JSON without writing entity classes manually
Jackson XML is directly converted to JSON without writing entity classes manually
2022-06-12 06:54:00 【ldj2020】
Warning : At present, tests on different computers are not very stable , I am glad that the test was successful , Sometimes Chinese garbled code appears (idea Tool configuration related ), Another serious problem is When parsing a with an array xml when , Elements of the same type in the array will be treated as a parse , Cause incomplete data , As in this example student object ;
reason :springboot The version of is too low , requirement 2.4.5 above ;fastjson There are also such problems , So it's not recommended here , If the inspector insists on using fastjson, It can be provided by the owner 1.2.76, As if 1.2.75 It's fine too , Forget the .
There can be another way , Is to introduce org.json rely on , Use XML.toJSONObject(String xml) Method , Analytic logic is the same as the first pure jackson The writing is similar , The code is a bit long but not complicated , If you find a problem, you can raise it , I will follow up .
A pit : When springboot The dependent version of the parent project is 2.4.5 when
JsonNode jsonNode = xmlMapper.readValue(newXML, JsonNode.class); The breakpoint result is shown in the following figure

It is also written like this JsonNode jsonNode = xmlMapper.readValue(newXML, ObjectNode.class);
We can know from the source code ,ObjectNode yes JsonNod Derived inheritance classes .
Test the successful dependent version :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jt</groupId>
<artifactId>springboot_demo_4</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- Import parent project -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath/>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--thymeleaf Import template tool class -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--SpringMVCjar Package file -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Hot deployment tools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--lombok plug-in unit -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Test package -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- introduce jdbc package -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- Introduce database driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--spring Integrate mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
</dependencies>
<!-- Responsible for project packaging and deployment -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.jt.test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.apache.commons.lang3.StringUtils;
import org.json.XML;
import java.util.HashMap;
import java.util.Map;
/**
* User: ldj
* Date: 2022/1/26
* Time: 21:24
* Description: xml Go straight to json
*/
public class XmlToJsonDemo {
public static void main(String[] args) {
// Object turn xml
String xml = "<Message>" +
" <School>" +
" <SchoolName> Straw hat middle school </SchoolName>" +
" </School>" +
" <Class>" +
" <ClassName> three 7 class </ClassName>" +
" <Level>" +
" <A>1</A>" +
" <B>2</B>" +
" </Level>" +
" <Person>" +
" <Teacher>" +
" <Name>LuLu</Name>" +
" <Gender> Woman </Gender>" +
" <Age>23</Age>" +
" </Teacher>" +
" <Student>" +
" <Name> Zhang San </Name>" +
" <Gender> male </Gender>" +
" <Age>16</Age>" +
" </Student>" +
" <Student>" +
" <Name> Li Si </Name>" +
" <Gender> male </Gender>" +
" <Age>17</Age>" +
" </Student>" +
" <Student>" +
" <Name> lily </Name>" +
" <Gender> Woman </Gender>" +
" <Age>16</Age>" +
" </Student>" +
" </Person>" +
" </Class>" +
"</Message>";
String age = "18";
int ages = Integer.parseInt(age);
System.out.println(ages);
System.out.println("\n");
System.out.println("=============================== xml -> json Node by node analysis ================================");
Map<String, String> responseMap = xmlToJson(xml);
String schoolJSON = responseMap.get("schoolJSON");
String classJSON = responseMap.get("classJSON");
System.out.println(schoolJSON);
System.out.println(classJSON);
System.out.println("\n");
System.out.println("=============================== xml -> json Full node resolution ================================");
System.out.println(getResponseJSON(xml, "Message"));
System.out.println("\n");
System.out.println("=================================org.json Node by node analysis ==========================================");
Map<String, String> responseMap1 = xml2Json(xml, "Message");
String schoolJSON1 = responseMap1.get("schoolJSON");
String classJSON1 = responseMap1.get("classJSON");
System.out.println(schoolJSON1);
System.out.println(classJSON1);
System.out.println("\n");
}
// Node by node resolution
private static Map<String, String> xmlToJson(String xml) {
XmlMapper xmlMapper = new XmlMapper();
HashMap<String, String> responseMap = new HashMap<>();
try {
JsonNode jsonNode = xmlMapper.readValue(xml, JsonNode.class);
JsonNode schoolNode = jsonNode.get("School");
JsonNode classNode = jsonNode.get("Class");
ObjectMapper objectMapper = new ObjectMapper();
if (schoolNode.isContainerNode()) {
String schoolJSON = objectMapper.writeValueAsString(schoolNode);
if (StringUtils.isNotBlank(schoolJSON)) {
responseMap.put("schoolJSON", schoolJSON);
}
}
if (classNode.isContainerNode()) {
String classJSON = objectMapper.writeValueAsString(classNode);
if (StringUtils.isNotBlank(classJSON)) {
responseMap.put("classJSON", classJSON);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return responseMap;
}
// Analyze all
private static String getResponseJSON(String xml, String rootTag) {
// Right in xml Add the root node label <Tag></Tag>
String s1 = "<" + rootTag + ">";
String s2 = "</" + rootTag + ">";
StringBuilder sb = new StringBuilder(xml.replaceAll("\\s*", ""));
int indexStart = sb.indexOf(s1);
sb.insert(indexStart + (s1.length()), "<Tag>");
int indexEnd = sb.indexOf(s2);
sb.insert(indexEnd, "</Tag>");
String newXML = sb.toString();
String responseJSON = null;
XmlMapper xmlMapper = new XmlMapper();
try {
//JsonNode jsonNode = xmlMapper.readValue(newXML, JsonNode.class);
JsonNode jsonNode = xmlMapper.readValue(newXML, ObjectNode.class);
JsonNode schoolNode = jsonNode.get("Tag");
ObjectMapper objectMapper = new ObjectMapper();
if (schoolNode.isContainerNode()) {
String json = objectMapper.writeValueAsString(schoolNode);
if (StringUtils.isNotBlank(json)) {
responseJSON = json;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return responseJSON;
}
// Use org.json + jackson package perhaps org.json + fastjson package < Not recommended >
private static Map<String, String> xml2Json(String xml, String rootTag) {
HashMap<String, String> responseMap = new HashMap<>();
// Remove the root tag Message, If you don't remove the root tag Message, The generated data structure is "Message":{.....}
if (StringUtils.isNotBlank(rootTag)) {
xml = xml.replace("<" + rootTag + ">", "");
xml = xml.replace("</" + rootTag + ">", "");
}
try {
org.json.JSONObject json = XML.toJSONObject(xml);
/**
* Due to version issues , When parsing a with an array xml when , Treat elements of the same type in the array as a parse , Cause incomplete data , Still use the original jackson package
* com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(json.toString());
* String schoolNode = jsonObject.getString("School");
* String classNode = jsonObject.getString("Class");
*/
/*
* In fact, the first method above XmlMapper() Is inherited ObjectMapper 《 Source code 》 So the following two lines of code are equivalent to
* XmlMapper xmlMapper = new XmlMapper();
* JsonNode jsonNode = xmlMapper.readValue(xml, JsonNode.class);
* ObjectNode yes JsonNod Derived inheritance classes
*/
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readValue(json.toString(), JsonNode.class);
if (jsonNode.isContainerNode()) {
JsonNode schoolNode = jsonNode.get("School");
JsonNode classNode = jsonNode.get("Class");
if (schoolNode.isContainerNode()) {
responseMap.put("schoolJSON", schoolNode.toString());
}
if (classNode.isContainerNode()) {
responseMap.put("classJSON", classNode.toString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return responseMap;
}
}
//jason It can also be read as Tree, I don't know that the performance will remain high , Never tested
private static HashMap<String, String> getResponseTree(String xml){
XmlMapper xmlMapper = new XmlMapper();
HashMap<String, String> responseMap = new HashMap<>();
try {
JsonNode jsonNode = xmlMapper.readTree(xml.getBytes(StandardCharsets.UTF_8));
if(jsonNode.isContainerNode()){
JsonNode schoolNode = jsonNode.get("School");
JsonNode classNode = jsonNode.get("Class");
ObjectMapper objectMapper = new ObjectMapper();
if (schoolNode.isContainerNode()) {
//responseMap.put("schoolJSON", schoolNode.toString());
String schoolJSON = objectMapper.writeValueAsString(schoolNode);
if (StringUtils.isNotBlank(schoolJSON)) {
responseMap.put("schoolJSON", schoolJSON);
}
}
if (classNode.isContainerNode()) {
String classJSON = objectMapper.writeValueAsString(classNode);
if (StringUtils.isNotBlank(classJSON)) {
responseMap.put("classJSON", classJSON);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return responseMap;
} 
I want the number type and I use the first way , What do I do ?
String age = "18";
int ages = Integer.parseInt(age);
System.out.println(ages);
Use org.json
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
private static String xtj(String xml) {
JSONObject json = XML.toJSONObject(xml);
return json.toString();
}If there is Chinese garbled code, you can set it like this

边栏推荐
- How to build your own website (using the pagoda panel)
- The seventh day of June training - hash table
- sql server2019安装到这步无法进行下一步了,如何解决?
- sql server 2019安装出现错误,如何解决
- LeetCode-1873. Calculate special bonus
- The second revolution of reporting tools
- SQL Server 2019 installation error. How to solve it
- 张驰课堂:2022年CAQ中质协六西格玛考试时间通知
- LeetCode-1350. Invalid students
- “我被大厂裁员了”
猜你喜欢

(14)Blender源码分析之闪屏窗口显示软件版本号

8 IO Library

Tomato learning notes-stm32 SPI introduction and Tim synchronization

VSCode常用插件

Solution: content type 'application/x-www-form-urlencoded; charset=UTF-8‘ not supported

Reentrantlock underlying AQS source code analysis

最近面了15个人,发现这个测试基础题都答不上来...

About session Getattribute, getattribute error

When SQL server2019 is installed, the next step cannot be performed. How to solve this problem?

leetcode:剑指 Offer 67. 把字符串转换成整数【模拟 + 分割 +讨论】
随机推荐
d不能用非常ctfe指针
【图像去噪】基于非局部欧几里德中值 (NLEM) 实现图像去噪附matlab代码
美团获得小样本学习榜单FewCLUE第一!Prompt Learning+自训练实战
8. form label
库里扛起了勇士对凯尔特人的第四场
Host computer development (firmware download software requirement analysis)
sql server2019安装到这步无法进行下一步了,如何解决?
Tomato learning notes -seq2seq
Oracle Database
The first day of June training - array
Detailed explanation of convirt paper (medical pictures)
Tomato learning notes -vscade configuring makefile (using task.jason and launch.jason)
Set [list] to find out the subscript of repeated elements in the list (display the position of the subscript)
Tomato learning notes-stm32 SPI introduction and Tim synchronization
Database syntax related problems, solve a correct syntax
postman拼接替换参数循环调用接口
[image denoising] salt and pepper noise image denoising based on Gaussian filter, mean filter, median filter and bilateral filter with matlab code attached
张驰咨询:流程是一剂万能良药吗?
VSCode常用插件
张驰课堂:2022年CAQ中质协六西格玛考试时间通知