Moshi: Document how to use Moshi with java.io.OutputStream & java.io.InputStream

Created on 1 Apr 2021  路  4Comments  路  Source: square/moshi

I'm writing code to serialize JSON objects to java.io.OutputStream and deserialize from java.io.InputStream.

I searched for 20 mins for the way to pass an OutputStream to JsonAdapter<?>::toJson(). Let's put the answer in the docs to help others:

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import okio.BufferedSink;
import okio.Okio;

static <T> T fromJson(Class<T> clazz, InputStream inputStream) throws IOException {
  Moshi moshi = new Moshi.Builder().build();
  JsonAdapter<T> adapter = moshi.adapter(clazz);
  return adapter.fromJson(Okio.buffer(Okio.source(inputStream)));
}

static <T> void toJson(T obj, OutputStream outputStream) throws IOException {
  Moshi moshi = new Moshi.Builder().build();
  @SuppressWarnings("unchecked")
  JsonAdapter<T> adapter = moshi.adapter((Class<T>) obj.getClass());
  BufferedSink out = Okio.buffer(Okio.sink(outputStream));
  adapter.toJson(out, obj);
  out.flush();  // Also flushes `outputStream`.
}
enhancement

All 4 comments

Moshi uses Okio and Okio has plenty of docs on how to interop with those types 馃憤

Can you please point me to the "plenty of docs on how to interop with those types"?

https://square.github.io/okio/ has no code showing how to use Okio types with InputStream or OutputStream. There is a little snippet showing reading from a Socket.

Are there some other docs I could have found during my search?

Did you try the search on the site? It's pretty handy and points to here https://square.github.io/okio/#sources-and-sinks. If you then look at the Source and Sink APIs + extensions, it's the first one on both source and sink.

image

image

I filed this issue to tell you about my problem as a new user of Moshi. The purpose of the documentation is to help people like me. It seems to me that you're not interested in iterating on your documentation to make it better meet the needs of its users. That's ok. Maintaining an open source project is tiring. Most people burn out quickly while doing that job. How about searching for someone else to help maintain it? You could take a break.

Was this page helpful?
0 / 5 - 0 ratings