title: Serialize large Java Object to Json Strings
body: <p>I have a large Java object (100MB+) that needs to be serialized to Json string. I was using jackson Json until I found out it reaches memory limit on large object:</p>
  
  <pre><code>Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
      at java.util.Arrays.copyOfRange(Arrays.java:3664)
      at java.lang.String.&lt;init&gt;(String.java:207)
      at java.lang.StringBuilder.toString(StringBuilder.java:407)
      at com.fasterxml.jackson.core.util.TextBuffer.contentsAsString(TextBuffer.java:349)
      at com.fasterxml.jackson.core.io.SegmentedStringWriter.getAndClear(SegmentedStringWriter.java:83)
      at com.fasterxml.jackson.databind.ObjectWriter.writeValueAsString(ObjectWriter.java:682)
      at JavaTest.objToJson(JavaTest.java:76)
  </code></pre>
  
  <p>The method that does the conversion looks like this:</p>
  
  <pre><code>public static String objToJson(Object obj) {
  
      ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
      String json = null;
  
      try {
          json = ow.writeValueAsString(obj);
      } catch (JsonProcessingException e) {
          System.out.println("Error in objToJson(): " + e);
          e.getMessage();
          e.printStackTrace();
      }
      return json;
  }
  </code></pre>
  
  <p>The environment is memory intense so that I won't be able to arbitrarily increase the heap size.</p>
  
  <p>Any suggestions on more memory efficient ways of serializing Java objects? I found jackson library can do streaming but many posts say about the other way around, i.e., deserializing json string to object. Also, it seems jackson lib has better performance than other packages such as gson, which I haven't tried personally.</p>
  
  <p>Thanks.</p>