@Override public RequestBody toBody(T value) { Buffer buffer = new Buffer(); Writer writer = new OutputStreamWriter(buffer.outputStream(), Util.UTF_8); try { typeAdapter.toJson(writer, value); writer.flush(); } catch (IOException e) { throw new AssertionError(e); // Writing to Buffer does no I/O. } return RequestBody.create(MEDIA_TYPE, buffer.readByteString()); }
/** * Converts {@code value} to a JSON document. Unlike Gson's similar {@link Gson#toJson(Object) * toJson} method, this write is strict. Create a {@link JsonWriter#setLenient(boolean) lenient} * {@code JsonWriter} and call {@link #write(com.google.gson.stream.JsonWriter, Object)} for * lenient writing. * * @param value the Java object to convert. May be null. * @since 2.2 */ public final String toJson(T value) throws IOException { StringWriter stringWriter = new StringWriter(); toJson(stringWriter, value); return stringWriter.toString(); }
public void testRenamedFields() throws IOException { TypeAdapter<RenamedFields> adapter = parameterizedCtorFactory.create(gson, TypeToken.get(RenamedFields.class)); assertEquals(new RenamedFields(0, 1), adapter.fromJson("{\"foo\":0,\"_bar\":1}")); assertEquals(adapter.toJson(new RenamedFields(0, 1)), "{\"foo\":0,\"_bar\":1}"); }