xml文件转成json文件的Java代码
时间: 2023-04-03 08:05:10 浏览: 88
可以使用第三方库,比如Jackson或者Gson来实现xml文件转成json文件的Java代码。具体实现可以参考这篇博客:https://www.cnblogs.com/softidea/p/10627422.html
相关问题
xml文件转换成json的java示例代码
以下是使用Jackson库将XML文件转换为JSON格式的Java示例代码:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.File;
import java.io.IOException;
public class XmlToJsonConverter {
public static void main(String[] args) throws IOException {
// 1. 解析XML文件,得到Java对象
File xmlFile = new File("input.xml"); // XML文件路径
XmlMapper xmlMapper = new XmlMapper();
MyObject myObject = xmlMapper.readValue(xmlFile, MyObject.class);
// 2. 将Java对象转换为JSON格式的字符串
ObjectMapper jsonMapper = new ObjectMapper();
jsonMapper.enable(SerializationFeature.INDENT_OUTPUT); // 格式化输出
String jsonString = jsonMapper.writeValueAsString(myObject);
// 3. 输出JSON格式的字符串
System.out.println(jsonString);
}
}
// 定义Java对象与XML文件的映射关系
class MyObject {
private String name;
private int age;
private String address;
// getter和setter方法省略
}
```
在上面的示例代码中,输入文件为名为`input.xml`的XML文件,输出为JSON格式的字符串。首先使用`XmlMapper`将XML文件解析为Java对象,然后使用`ObjectMapper`将Java对象序列化为JSON格式的字符串。在序列化过程中,使用了`SerializationFeature.INDENT_OUTPUT`选项来格式化输出。最后将JSON格式的字符串输出到控制台。需要注意的是,`MyObject`类需要与XML文件中的元素名相对应,可以使用注解或配置文件来指定映射规则。
java实现把xml文件转换成json文件
可以使用第三方库 `org.json` 和 `javax.xml` 来实现将 XML 文件转换成 JSON 文件。
示例代码:
```java
import org.json.JSONObject;
import org.json.XML;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
public class XmlToJson {
public static void main(String[] args) throws Exception {
// 读取 XML 文件
String xml = new String(Files.readAllBytes(new File("input.xml").toPath()), StandardCharsets.UTF_8);
// 将 XML 转换成 JSON
JSONObject json = XML.toJSONObject(xml);
// 将 JSON 写入文件
try (FileWriter file = new FileWriter("output.json")) {
file.write(json.toString());
}
}
}
```
其中,`XML.toJSONObject()` 方法将 XML 转换成 JSON,`JSONObject.toString()` 方法将 JSON 转换成字符串,然后写入文件中。