在Java中,可以使用第三方库如GZIP或Deflate来压缩JSON数据。以下是使用这两种方法的示例:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import org.json.JSONObject;
public class GzipCompress {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("key", "value");
try {
byte[] compressedData = compress(jsonObject.toString());
System.out.println("Compressed data: " + new String(compressedData));
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] compress(String data) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
gzipOutputStream.write(data.getBytes());
gzipOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
}
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import org.json.JSONObject;
public class DeflateCompress {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("key", "value");
try {
byte[] compressedData = compress(jsonObject.toString());
System.out.println("Compressed data: " + new String(compressedData));
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] compress(String data) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Deflater deflater = new Deflater();
deflater.setInput(data.getBytes());
deflater.finish();
byte[] buffer = new byte[1024];
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
byteArrayOutputStream.write(buffer, 0, count);
}
byteArrayOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
}
这两个示例都使用了org.json库来创建JSON对象。你可以使用Maven或Gradle将其添加到项目中:
Maven:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
Gradle:
implementation 'org.json:json:20210307'
注意:压缩后的数据通常是二进制格式,因此在将其转换为字符串时可能会出现乱码。在实际应用中,建议将压缩后的数据存储在文件或字节流中,并在需要时进行解压缩。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。