title: Serializing Java 8 Streams
body: <p>I would like to use Jackson to serialize the output from a stream. Jackson does not have intrinsic support for serializing <code>java.util.stream.Stream</code>, but it is capable of serializing <code>java.util.Iterator</code>.</p>
  
  <p>To illustrate the problem, I would like to serialize this trivial interface:</p>
  
  <pre><code>public interface SerializeMe {
      Iterator&lt;Integer&gt; getMyNumbers();
  }
  </code></pre>
  
  <p>I will be comparing the output from serializing <code>List.iterator()</code> vs. <code>Stream.iterator()</code>:</p>
  
  <pre><code>public class SerializeViaList implements SerializeMe {
      @Override
      public Iterator&lt;Integer&gt; getMyNumbers() {
          return Arrays.asList(1, 2, 3).iterator();
      }
  }
  
  public class SerializeViaStream implements SerializeMe {
      @Override
      public Iterator&lt;Integer&gt; getMyNumbers() {
          return Arrays.asList(1, 2, 3).stream().iterator();
      }
  }
  </code></pre>
  
  <p>The following method will demonstrate the output from these two classes:</p>
  
  <pre><code>public static void main(String[] args) throws Exception {
      ObjectMapper mapper = new ObjectMapper();
  
      System.out.println("via list: " + mapper.writeValueAsString(new SerializeViaList()));
      System.out.println("via stream: " + mapper.writeValueAsString(new SerializeViaStream()));
  }
  </code></pre>
  
  <p>The output from this is:</p>
  
  <pre><code>via list: {"myNumbers":[1,2,3]}
  via stream: {"myNumbers":{}}
  </code></pre>
  
  <p>This demonstrates that the stream iterator is not correctly serialized. </p>
  
  <p>Interestingly, it <em>does</em> work if i add <code>@JsonSerialize(as=Iterator.class)</code>:</p>
  
  <pre><code>@JsonSerialize(as=Iterator.class)
  public Iterator&lt;Integer&gt; getMyNumbers() {
      // ....
  }
  </code></pre>
  
  <p>I don't want to have to write a custom <code>JsonSerializer</code> for every type iterator that a stream can create. What are my alternatives?</p>