Java Code Examples for com.squareup.moshi.JsonAdapter#toJson()

The following examples show how to use com.squareup.moshi.JsonAdapter#toJson() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PolymorphicJsonAdapterFactoryTest.java    From moshi with Apache License 2.0 6 votes vote down vote up
@Test public void unregisteredSubtype() {
  Moshi moshi = new Moshi.Builder()
      .add(PolymorphicJsonAdapterFactory.of(Message.class, "type")
          .withSubtype(Success.class, "success")
          .withSubtype(Error.class, "error"))
      .build();
  JsonAdapter<Message> adapter = moshi.adapter(Message.class);

  try {
    adapter.toJson(new EmptyMessage());
  } catch (IllegalArgumentException expected) {
    assertThat(expected).hasMessage("Expected one of [class"
        + " com.squareup.moshi.adapters.PolymorphicJsonAdapterFactoryTest$Success, class"
        + " com.squareup.moshi.adapters.PolymorphicJsonAdapterFactoryTest$Error] but found"
        + " EmptyMessage, a class"
        + " com.squareup.moshi.adapters.PolymorphicJsonAdapterFactoryTest$EmptyMessage. Register"
        + " this subtype.");
  }
}
 
Example 2
Source File: SerializeNullsJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void serializesNulls() throws Exception {
  JsonAdapter<Data1> adapter = moshi.adapter(Data1.class);

  Data1 fromJson = adapter.fromJson("{\n"
      + "  \"data\": null\n"
      + "}");
  assertThat(fromJson.data).isNull();

  String toJson = adapter.toJson(fromJson);
  assertThat(toJson).isEqualTo("{\"data\":null}");
}
 
Example 3
Source File: WrappedJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void factoryFetchesWrappedFromDelegate() throws Exception {
  JsonAdapter<Data5> adapter = moshi.adapter(Data5.class);

  Data5 fromJson = adapter.fromJson("{\n"
          + "  \"str\": {\n"
          + "    \"1\": \"test\"\n"
          + "  }\n"
          + "}");
  assertThat(fromJson.str).isEqualTo("test");

  String toJson = adapter.toJson(fromJson);
  assertThat(toJson).isEqualTo("{\"str\":{\"1\":\"test\"}}");
}
 
Example 4
Source File: ModelListAdapter.java    From android with Apache License 2.0 5 votes vote down vote up
@Override public void toJson(JsonWriter writer, List<T> value) throws IOException {
  writer.beginObject();
  writer.name(type.getSimpleName().toLowerCase());
  writer.beginArray();
  JsonAdapter<T> adapter = moshi.adapter(type);
  for (T n : value) {
    adapter.toJson(writer, n);
  }
  writer.endArray();
  writer.endObject();
}
 
Example 5
Source File: FirstElementJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
private void assertNullReturn(String string) throws IOException {
  JsonAdapter<Data> adapter = moshi.adapter(Data.class);

  Data fromJson = adapter.fromJson(string);
  assertThat(fromJson.str).isNull();

  String toJson = adapter.toJson(fromJson);
  assertThat(toJson).isEqualTo("{\"obj\":[null]}");
}
 
Example 6
Source File: WrappedJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void arrayOfObjects() throws Exception {
  JsonAdapter<List<Data2>> adapter = moshi.adapter(
      Types.newParameterizedType(List.class, Data2.class));

  List<Data2> fromJson = adapter.fromJson("[\n"
      + "  {\n"
      + "    \"data\": {\n"
      + "      \"1\": {\n"
      + "        \"2\": {\n"
      + "          \"str\": \"funny\",\n"
      + "          \"val\": 42\n"
      + "        }\n"
      + "      }\n"
      + "    }\n"
      + "  },\n"
      + "  {\n"
      + "    \"data\": {\n"
      + "      \"1\": {\n"
      + "        \"2\": {\n"
      + "          \"str\": \"prime\",\n"
      + "          \"val\": 43\n"
      + "        }\n"
      + "      }\n"
      + "    }\n"
      + "  }\n"
      + "]");
  assertThat(fromJson.get(0).data.str).isEqualTo("funny");
  assertThat(fromJson.get(0).data.val).isEqualTo(42);
  assertThat(fromJson.get(1).data.str).isEqualTo("prime");
  assertThat(fromJson.get(1).data.val).isEqualTo(43);

  String toJson = adapter.toJson(fromJson);
  assertThat(toJson).isEqualTo("["
      + "{\"data\":{\"1\":{\"2\":{\"str\":\"funny\",\"val\":42}}}},"
      + "{\"data\":{\"1\":{\"2\":{\"str\":\"prime\",\"val\":43}}}}"
      + "]");
}
 
Example 7
Source File: FallbackOnNullJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
private <T extends Wrapper<P>, P> void assertForClass(Class<T> cls, P first, P second,
    String asJson) throws IOException {
  JsonAdapter<T> adapter = moshi.adapter(cls);

  T fromJson = adapter.fromJson("{\n"
      + "  \"first\": null,\n"
      + "  \"second\": null\n"
      + "}");
  assertThat(fromJson.first()).isEqualTo(first);
  assertThat(fromJson.second()).isEqualTo(second);

  String toJson = adapter.toJson(fromJson);
  assertThat(toJson).isEqualTo(asJson);
}
 
Example 8
Source File: FallbackOnNullJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void factoryMaintainsOtherAnnotations() throws Exception {
  JsonAdapter<AnotherInt> adapter = moshi.adapter(AnotherInt.class);

  AnotherInt fromJson = adapter.fromJson("{\n"
      + "  \"willFallback\": null,\n"
      + "  \"willMultiply\": 3\n"
      + "}");
  assertThat(fromJson.willFallback).isEqualTo(2);
  assertThat(fromJson.willMultiply).isEqualTo(6);

  String toJson = adapter.toJson(fromJson);
  // Both values should be serialized by the Multiply json adapter.
  assertThat(toJson).isEqualTo("{\"willFallback\":1,\"willMultiply\":3}");
}
 
Example 9
Source File: SerializeNullsJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void maintainsPreviousSerializationValue() throws Exception {
  JsonAdapter<Data1> adapter = moshi.adapter(Data1.class);
  Data1 data1 = new Data1();

  JsonWriter writer1 = JsonWriter.of(new Buffer());
  writer1.setSerializeNulls(true);
  adapter.toJson(writer1, data1);
  assertThat(writer1.getSerializeNulls()).isTrue();

  JsonWriter writer2 = JsonWriter.of(new Buffer());
  writer2.setSerializeNulls(false);
  adapter.toJson(writer2, data1);
  assertThat(writer2.getSerializeNulls()).isFalse();
}
 
Example 10
Source File: MoshiMessageBodyWriter.java    From jax-rs-moshi with Apache License 2.0 5 votes vote down vote up
@Override public void writeTo(Object o, Class<?> type, Type genericType, Annotation[] annotations,
    MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
    throws IOException, WebApplicationException {
  JsonAdapter<Object> adapter = moshi.adapter(genericType);
  BufferedSink sink = Okio.buffer(Okio.sink(entityStream));
  adapter.toJson(sink, o);
  sink.emit();
  // Note: we do not close the OutputStream per the interface documentation.
}
 
Example 11
Source File: ElementAtJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
private void assertNullReturn(String string) throws IOException {
  JsonAdapter<Data> adapter = moshi.adapter(Data.class);

  Data fromJson = adapter.fromJson(string);
  assertThat(fromJson.str).isNull();

  String toJson = adapter.toJson(fromJson);
  assertThat(toJson).isEqualTo("{\"obj\":[null]}");
}
 
Example 12
Source File: ElementAtJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void elementAtDelegated() throws Exception {
  JsonAdapter<Data3> adapter = moshi.adapter(Data3.class);

  Data3 fromJson = adapter.fromJson("{\n"
          + "  \"obj\": [\n"
          + "    \"one\",\n"
          + "    \"two\"\n"
          + "  ]\n"
          + "}");
  assertThat(fromJson.str).isEqualTo("two");

  String toJson = adapter.toJson(fromJson);
  assertThat(toJson).isEqualTo("{\"obj\":[\"two\"]}");
}
 
Example 13
Source File: WriteJson.java    From moshi with Apache License 2.0 5 votes vote down vote up
public void run() throws Exception {
  BlackjackHand blackjackHand = new BlackjackHand(
      new Card('6', SPADES),
      Arrays.asList(new Card('4', CLUBS), new Card('A', HEARTS)));

  Moshi moshi = new Moshi.Builder().build();
  JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class);

  String json = jsonAdapter.toJson(blackjackHand);
  System.out.println(json);
}
 
Example 14
Source File: RenameUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSerializing_thenFieldsGetRenamed() {
    Moshi moshi = new Moshi.Builder()
      .build();
    JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);

    Post post = new Post("My Post", "Baeldung");
    String json = jsonAdapter.toJson(post);
    System.out.println(json);
}
 
Example 15
Source File: LastElementJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
private void assertNullReturn(String string) throws IOException {
  JsonAdapter<LastElementJsonAdapterTest.Data> adapter = moshi.adapter(Data.class);

  LastElementJsonAdapterTest.Data fromJson = adapter.fromJson(string);
  assertThat(fromJson.str).isNull();

  String toJson = adapter.toJson(fromJson);
  assertThat(toJson).isEqualTo("{\"obj\":[null]}");
}
 
Example 16
Source File: ComplexAdapterUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSerializing_thenCorrectJsonProduced() {
    Moshi moshi = new Moshi.Builder()
      .add(new JsonDateTimeAdapter())
      .build();
    JsonAdapter<ZonedDateTime> jsonAdapter = moshi.adapter(ZonedDateTime.class);

    String json = jsonAdapter.toJson(ZonedDateTime.now());
    System.out.println(json);
}
 
Example 17
Source File: JsonBuffer.java    From moshi-jsonapi with MIT License 5 votes vote down vote up
public static <T> JsonBuffer<T> create(JsonAdapter<T> adapter, T value) {
    try {
        Buffer buffer = new Buffer();
        adapter.toJson(buffer, value);
        return new JsonBuffer<>(buffer.readByteArray());
    } catch (IOException e) {
        throw new RuntimeException("JsonBuffer failed to serialize value with [" + adapter.getClass() + "]", e);
    }
}
 
Example 18
Source File: MoshiSpeaker.java    From Jolyglot with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override public String toJson(Object src)  {
  JsonAdapter<Object> jsonAdapter = moshi.adapter(Object.class);
  return jsonAdapter.toJson(src);
}
 
Example 19
Source File: MultipleFormats.java    From moshi with Apache License 2.0 4 votes vote down vote up
@ToJson void toJson(JsonWriter writer, Card value,
    @CardString JsonAdapter<Card> stringAdapter) throws IOException {
  stringAdapter.toJson(writer, value);
}
 
Example 20
Source File: JsonHelper.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
public static <K> String serializeToJson(K o, Type type) {
    JsonAdapter<K> jsonAdapter = MOSHI.adapter(type);

    return jsonAdapter.toJson(o);
}