Search code examples
javajsonjava-streamgson

Is it possible to pass a java.util.Stream to Gson?


I'm currently working on a project where I need to fetch a large amount of data from the database and parse it into a specific JSON format. I already have built my custom Serializers and it's working properly when I pass a List<MyObject> to Gson.

As I was already working with streams from my JPA layer, I thought I could pass the Stream down to the Gson parser so that it could transform it directly to my Json data. But I'm getting an empty JSON object instead of a correctly populated one.

Can anyone point me to a way to make Gson work with Java 8 streams, or whether this isn't possible currently? I could not find anything on Google.


Solution

  • You could use JsonWriter to streaming your data to output stream:

    public void writeJsonStream(OutputStream out, Stream<DataObject> data) throws IOException {
         try(JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"))) {
              writer.setIndent("    ");
              writer.beginArray();
              data.forEach(d -> {
                  d.beginObject();
                  d.name("yourField").value(d.getYourField());
                  ....
                  d.endObject();
              });
              writer.endArray();
         }
    }
    

    Note that you're in charge of controling the json structure.

    That is, if your DataObject contains nested Object, you have to write beginObject()/endObject() respectively. The same goes for nested array.