我想使用JAVA 将JSON对象列表转换为gzip文件
下面是我的JSON文件
[
{
"id": "01",
"Status": "Open",
"siteId": "01",
"siteName": "M1"
},
{
"id": "02",
"Status": "Open",
"siteId": "02",
"siteName": "M2"
},
{
"id": "03",
"Status": "Open",
"siteId": "03",
"siteName": "M3"
}
]
迄今为止编写的代码:
public static void main(String args[]) throws IOException
{
final ObjectMapper objectMapper = new ObjectMapper();
String fileName = "jsonList.json";
ClassLoader classLoader = className.class.getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
System.out.println("File Found : " + file.exists());
List<document> list = objectMapper.readValue(file,new TypeReference<List<document>>(){});
System.out.println("List of json objects");
//code to compress list of json objects (list)
}
文件类
public class document {
public String id;
public String status;
public String sideId;
public String siteName;
}
请给我推荐压缩列表的代码谢谢
你可以使用这样的东西,StudentL:
OutputStream outputStream = new FileOutputStream("output_file.zip");
GZIPOutputStream gzipOuputStream = new GZIPOutputStream(outputStream);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(gzipOuputStream);
for (Document doc : list) {
objectOutputStream.writeObject(doc);
}
objectOutputStream.close();
我想这是一个练习,否则就认为你所做的没有那么多意义。您不需要读取JSON并执行整个解组操作;您可以简单地获取现有文件并对其进行gzip。
额外的编辑:代码中有两件事往往会激怒Java开发人员。首先,在Java中,类的名称通常是用Camel大小写的。第二个是,不要像在C/C++和其他语言中那样,在大括号之前使用换行符。
错误:
public class Whatever
{
右:
public class Whatever {
回头见!
以下是我认为您可以做的:
List<Map<String, String>> jsonList = ...;
// Create a FileOutputStream
FileOutputStream fileOutputStream
= new FileOutputStream("/path/to/file");
// Wrap the FileOutputStream in a BufferedOutputStream
// so that we write in larger chunks for performance
BufferedOutputStream bufferedOutputStream
= new BufferedOutputStream(fileOutputStream);
// Wrap the BufferedOutputStream in a GIZPOutputStream
// so that when we write to the gzipOutputStream,
// we first compress then buffer then write to the file.
GZIPOutputStream compressedOutputStream
= new GZIPOutputStream(bufferedOutputStream);
// Write the JSON map into the compressedOutputStream
objectMapper.writeValue(compressedOutputStream, jsonList);
这是你可以参考的杰克逊图书馆;下面是使用对象映射器和OutputStreams将对象压缩到文件的详细说明。