java xml转json
时间: 2023-06-29 17:02:51 浏览: 111
xml转json java
5星 · 资源好评率100%
你可以使用现成的Java库来将XML数据转换为JSON格式。以下是使用Jackson库的示例代码:
1. 添加Jackson依赖
```xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.0</version>
</dependency>
```
2. 编写转换代码
```java
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;
public class XmlToJsonConverter {
public static void main(String[] args) throws Exception {
String xml = "<root><name>John</name><age>30</age></root>";
// Create ObjectMapper instances for XML and JSON
XmlMapper xmlMapper = new XmlMapper();
ObjectMapper jsonMapper = new ObjectMapper();
// Convert XML to JSON
JsonNode jsonNode = xmlMapper.readTree(xml);
ObjectNode objectNode = jsonMapper.createObjectNode();
objectNode.setAll((ObjectNode) jsonNode);
// Print JSON output
System.out.println(objectNode.toString());
}
}
```
此代码将XML字符串转换为JSON字符串,并将其打印到控制台。你可以根据你的需求对输出进行处理。
阅读全文