Interoperability between XML and Javabeans in SpringBoot and FAQ
1. Procedure
1.0 Introducing dependencies
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11.1</version>
</dependency>
Copy the code
2. Use annotations for entities written for XML
XML file contents:
<messageList>
<public>
<requestTime>20210825121212</requestId>
<requestUser>I'm Liang Feifan</sendTime>
</public>
<curriculumList>
<curriculum>
<courseNo>100001</courseNo>
<achievement>100</achievement>
</curriculum>
<curriculum>
<courseNo>100002</courseNo>
<achievement>90</achievement>
</curriculum>
</curriculumList>
</messageList>
Copy the code
entity
@Data
@XStreamAlias("message")
public class UserMessage implements Serializable {
private static final long serialVersionUID = 1L;
@XStreamAlias("public")
private PublicMessage publicMessage;
@XStreamAlias("curriculumList")
private List<Curriculum> curriculumList;
Copy the code
@Data
@XStreamAlias("public")
public class PublicMessage implements Serializable {
private static final long serialVersionUID = 1L;
@XStreamAlias("requestTime")
private String requestTime;
@XStreamAlias("requestUser")
private String requestUser;
}
Copy the code
@Data
@XStreamAlias("curriculumList")
public class Curriculum {
@XStreamAlias("courseNo")
private String courseNo;
@XStreamAlias("achievement")
private String achievement;
}
Copy the code
The main notes involved
@XStreamAlias("courseNo")
Alias the XML node, consistent with the tag attribute of XML@XStreamImplicit(itemFieldName="courseNo")
: The tag attribute is List
3.0 Write XML to JavaBean tools
public static <T> T xmlToBean(String xmlStr, Class<T> cls) { XStream xstream = new XStream(); Xstream.setclassloader (cls.getClassLoader()); xstream.processAnnotations(cls); xstream.allowTypesByRegExp(new String[] { ".*" }); Object obj = xstream.fromXML(xmlStr); return (T) obj; }Copy the code
Note:
- appear
.java.lang.ClassCastException
The same entity cannot be transformed
Reason: Because it is not the default classloader used in the SpringBoot project. Solution: Manually reset xtream’s Classloader. Add the above code xstream.setClassLoader(cls.getClassLoader()); Where CLS is the class of entity transformation;
-
A com. Thoughtworks. Xstream. Security. ForbiddenClassException: com.jt.bean.xml.Com configParse problem,
Reason: Xsteam security permission verification mechanism
Solutions:
AllowTypes (new Class[]{no1. Class, no2. Class, no3. Class}); In this example, all classes are granted permission, so * is used;
Convert: UserMessage UserMessage = xmlToBean(xmlStr, usermessage.class); Through the above steps, the process of converting XML to bean is realized. Where xmlStr is a string of XML;
Turn the XML 4.0 bean
It is easier to call the String xmlStr = xtrem.toxml (p) method;