当前位置:网站首页>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

边栏推荐
- Set [list] to find out the subscript of repeated elements in the list (display the position of the subscript)
- 8. form label
- 六月集训 第二天——字符串
- 【图像去噪】基于非局部欧几里德中值 (NLEM) 实现图像去噪附matlab代码
- Reentrantlock underlying AQS source code analysis
- 数据库语法相关问题,求解一个正确语法
- Tomato learning notes -seq2seq
- Vscode Common plug - in
- Codeforces Round #793 (Div. 2) A B C
- d的自动无垃集代码.
猜你喜欢

It only takes 10 minutes to understand the underlying principle of NiO

新知识:Monkey 改进版之 App Crawler

SQL Server 2019 installation error. How to solve it

Codeforces Round #793 (Div. 2) A B C

企业微信官方 加解密库 PHP7版本报错 mcrypt_module_open 未定义方法 并且被PHP抛弃 解决方法使用 openssl解决

库里扛起了勇士对凯尔特人的第四场

张驰咨询:流程是一剂万能良药吗?

leetcode. 39 --- combined sum

"I was laid off by a big factory"

上传文件(post表单提交form-data)
随机推荐
Are you still using like+% for MySQL fuzzy query?
leetcode:剑指 Offer 67. 把字符串转换成整数【模拟 + 分割 +讨论】
8. 表单标签
leetcode.39 --- 组合总和
The seventh day of June training - hash table
LeetCode-1445. Apples and oranges
esp32 hosted
C language pointer
Scons编译IMGUI
PowerDesigner connects to entity database to generate physical model in reverse
【图像去噪】基于非局部欧几里德中值 (NLEM) 实现图像去噪附matlab代码
美团获得小样本学习榜单FewCLUE第一!Prompt Learning+自训练实战
Tomato learning notes-stm32 SPI introduction and Tim synchronization
SQL injection - Union query
The second revolution of reporting tools
Detailed explanation of convirt paper (medical pictures)
d中的解耦
leetcode:剑指 Offer 60. n个骰子的点数【数学 + 层次dp + 累计贡献】
ConVIRT论文详解(医疗图片)
Tomato learning notes -seq2seq