55import com .fasterxml .jackson .databind .DeserializationFeature ;
66import com .fasterxml .jackson .databind .ObjectMapper ;
77import com .fasterxml .jackson .databind .SerializationFeature ;
8- import com .fasterxml .jackson .dataformat .cbor .CBORFactory ;
98import com .fasterxml .jackson .datatype .jsr310 .JavaTimeModule ;
9+ import java .io .ByteArrayInputStream ;
10+ import java .io .ByteArrayOutputStream ;
11+ import java .io .IOException ;
1012import java .nio .charset .StandardCharsets ;
13+ import java .util .zip .GZIPInputStream ;
14+ import java .util .zip .GZIPOutputStream ;
1115
1216public class Serializer {
1317 public static final int MAX_STRING_LENGTH_ALLOWED = Integer .MAX_VALUE ;
1418 private static final ObjectMapper jsonMapper = new ObjectMapper ();
15- private static final ObjectMapper cborMapper = new ObjectMapper (new CBORFactory ());
1619
1720 static {
1821 configureMapper (jsonMapper );
19- configureMapper (cborMapper );
2022 }
2123
2224 private static void configureMapper (ObjectMapper mapper ) {
@@ -35,18 +37,40 @@ public static <T> T deserialize(byte[] data, TypeReference<T> typeReference) {
3537 // JSON format (backward compatibility)
3638 return jsonMapper .readValue (new String (data , StandardCharsets .UTF_8 ), typeReference );
3739 }
38- // CBOR format
39- return cborMapper .readValue (data , typeReference );
40+ // GZIP-compressed JSON format
41+ byte [] decompressed = decompress (data );
42+ return jsonMapper .readValue (new String (decompressed , StandardCharsets .UTF_8 ), typeReference );
4043 } catch (Exception e ) {
4144 throw new RuntimeException ("Failed to deserialize the object." , e );
4245 }
4346 }
4447
4548 public static <T > byte [] serialize (T object ) {
4649 try {
47- return cborMapper .writeValueAsBytes (object );
50+ return compress ( jsonMapper .writeValueAsBytes (object ) );
4851 } catch (Exception e ) {
4952 throw new RuntimeException ("Failed to serialize the object." , e );
5053 }
5154 }
55+
56+ private static byte [] compress (byte [] data ) throws IOException {
57+ ByteArrayOutputStream bos = new ByteArrayOutputStream (data .length );
58+ try (GZIPOutputStream gzip = new GZIPOutputStream (bos )) {
59+ gzip .write (data );
60+ }
61+ return bos .toByteArray ();
62+ }
63+
64+ private static byte [] decompress (byte [] data ) throws IOException {
65+ ByteArrayInputStream bis = new ByteArrayInputStream (data );
66+ try (GZIPInputStream gzip = new GZIPInputStream (bis )) {
67+ ByteArrayOutputStream bos = new ByteArrayOutputStream ();
68+ byte [] buffer = new byte [1024 ];
69+ int len ;
70+ while ((len = gzip .read (buffer )) != -1 ) {
71+ bos .write (buffer , 0 , len );
72+ }
73+ return bos .toByteArray ();
74+ }
75+ }
5276}
0 commit comments