xml字符串转JSON字符串,可以直接通过jackson提供的方法进行快速转换。在web项目中通常会引入spring-boot-starter-web
依赖。
但是spring-boot-starter-web
依赖包括Jackson的JSON处理库(如jackson-databind
、jackson-core
等),不一定直接包含处理XML的Jackson库(如jackson-dataformat-xml
),因此你可能需要额外引入依赖
<!-- 通过继承机制来间接指定版本号,同时避免Jackson的版本冲突 -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
xml字符串转JSON字符串,代码示例:
public static String convertXmlToJson(String xml) throws Exception {
XmlMapper xmlMapper = new XmlMapper();
JsonNode jsonNode = xmlMapper.readTree(xml);
ObjectMapper jsonMapper = new ObjectMapper();
// 将JsonNode转换为JSON字符串
return jsonMapper.writeValueAsString(jsonNode);
}
xml字符串转Java类对象,代码示例:
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
@JacksonXmlRootElement(localName = "user") // localName用以指定xml文档根元素的key
public class User {
private String name;
private int age;
// getter和setter省略
}
public class XmlConverter {
public static <T> T convertXmlToJavaObject(String xml, Class<T> clazz) throws Exception {
XmlMapper xmlMapper = new XmlMapper();
// 使用readValue方法将XML字符串反序列化为Java对象
return xmlMapper.readValue(xml, clazz);
}
public static void main(String[] args) {
String xml = "<user><name>John Doe</name><age>30</age></user>";
try {
User user = convertXmlToJavaObject(xml, User.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
标签:xml,jackson,String,JSON,字符串,public From: https://www.cnblogs.com/ashet/p/18420152