1 回答
TA贡献1872条经验 获得超3个赞
Excel
除非确实需要,否则不要生成文件。如果您想生成没有任何特定格式、图表、宏等的数据,只需生成CSV
包含纯数据的文件即可。要读取JSON
和生成,CSV
您可以使用支持这两种数据格式的Jackson库。假设你的JSON
样子如下:
{
"rows": [
{
"id": 1,
"name": "Vika",
"age": 27
},
{
"id": 2,
"name": "Mike",
"age": 28
}
]
}
您需要创建POJO适合该结构的模型,反序列化为JSON对象并将对象序列化以进行CSV格式化。示例解决方案如下所示:
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SequenceWriter;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.File;
import java.util.List;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper jsonMapper = new ObjectMapper();
Response response = jsonMapper.readValue(jsonFile, Response.class);
CsvMapper csvMapper = new CsvMapper();
CsvSchema schema = csvMapper.schemaFor(Item.class).withHeader();
SequenceWriter sequenceWriter = csvMapper.writer(schema).writeValues(System.out);
sequenceWriter.writeAll(response.getRows());
}
}
class Response {
private List<Item> rows;
// getters, setters
}
@JsonPropertyOrder({"id", "name", "age"})
class Item {
private int id;
private String name;
private int age;
// getters, setters
}
上面的代码打印:
id,name,age
1,Vika,27
2,Mike,28
添加回答
举报