Java实现JSON 转换 CSV 格式
时间: 2024-03-17 07:41:54 浏览: 131
可以使用现有的Java库,如Jackson或Gson,来实现JSON转换为CSV格式。以下是使用Jackson库进行转换的示例代码:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.File;
import java.io.IOException;
public class JsonToCsvConverter {
public static void main(String[] args) throws IOException {
// 读取JSON文件
ObjectMapper objectMapper = new ObjectMapper();
MyObject[] objects = objectMapper.readValue(new File("input.json"), MyObject[].class);
// 创建CSV格式
CsvMapper csvMapper = new CsvMapper();
CsvSchema csvSchema = csvMapper.schemaFor(MyObject.class).withHeader();
// 写入CSV文件
csvMapper.writer(csvSchema).writeValue(new File("output.csv"), objects);
}
}
class MyObject {
private String name;
private int age;
private String email;
// getters and setters
}
```
在这个例子中,我们读取名为“input.json”的JSON文件,并将其转换为MyObject类的数组。然后,我们使用CsvMapper和CsvSchema创建CSV格式,并将转换的对象写入名为“output.csv”的CSV文件中。请注意,MyObject类必须具有getter和setter方法,并且必须与JSON文件中的字段名称相同。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)