22
33import java .io .IOException ;
44import java .util .Arrays ;
5- import java .util .Map ;
65import java .util .List ;
6+ import java .util .Map ;
77
88import com .jsoniter .output .JsonStream ;
99import com .jsoniter .output .JsonStreamPool ;
@@ -15,7 +15,7 @@ private JsonSerializer() {
1515 }
1616
1717 /**
18- * Serialize an instance into a JSON object and return it as a byte array.
18+ * Serialize an instance into a byte array.
1919 *
2020 * @param obj the instance
2121 * @return the byte array
@@ -28,19 +28,31 @@ public static byte[] serialize(Object obj) {
2828 return Arrays .copyOfRange (stream .buffer ().data (), 0 , stream .buffer ().tail ());
2929 } catch (IOException e ) {
3030 throw new JsonException (e );
31- } finally {
32- JsonStreamPool .returnJsonStream (stream );
3331 }
3432 }
3533
3634 /**
37- * Serialize a map of strings into a JSON object and return it as a byte array.
35+ * Serialize an instance into a JSON stream.
36+ *
37+ * @param obj the instance
38+ * @param stream the JSON stream
39+ */
40+ public static void serialize (Object obj , JsonStream stream ) {
41+ try {
42+ stream .reset (null );
43+ stream .writeVal (obj .getClass (), obj );
44+ } catch (IOException e ) {
45+ throw new JsonException (e );
46+ }
47+ }
48+
49+ /**
50+ * Serialize a map of strings into a JSON stream.
3851 *
3952 * @param map the map
40- * @return the byte array
53+ * @param stream the JSON stream
4154 */
42- public static byte [] serialize (Map <String , String > map ) {
43- JsonStream stream = JsonStreamPool .borrowJsonStream ();
55+ public static void serialize (Map <String , String > map , JsonStream stream ) {
4456 try {
4557 stream .reset (null );
4658 stream .writeObjectStart ();
@@ -53,22 +65,18 @@ public static byte[] serialize(Map<String, String> map) {
5365 }
5466 });
5567 stream .writeObjectEnd ();
56- return Arrays .copyOfRange (stream .buffer ().data (), 0 , stream .buffer ().tail ());
5768 } catch (IOException e ) {
5869 throw new JsonException (e );
59- } finally {
60- JsonStreamPool .returnJsonStream (stream );
6170 }
6271 }
6372
6473 /**
65- * Serialize a list of objects into a JSON array and return it as a byte array .
74+ * Serialize a list of objects into a JSON stream .
6675 *
6776 * @param objs the list of objects
68- * @return the byte array
77+ * @param stream the JSON stream
6978 */
70- public static byte [] serialize (List <?> objs ) {
71- JsonStream stream = JsonStreamPool .borrowJsonStream ();
79+ public static void serialize (List <?> objs , JsonStream stream ) {
7280 try {
7381 stream .reset (null );
7482 stream .writeArrayStart ();
@@ -82,11 +90,8 @@ public static byte[] serialize(List<?> objs) {
8290
8391 }
8492 stream .writeArrayEnd ();
85- return Arrays .copyOfRange (stream .buffer ().data (), 0 , stream .buffer ().tail ());
8693 } catch (IOException e ) {
8794 throw new JsonException (e );
88- } finally {
89- JsonStreamPool .returnJsonStream (stream );
9095 }
9196 }
9297}
0 commit comments