You should add a JsonAdapter for the nested type t...
# squarelibraries
j
You should add a JsonAdapter for the nested type to your method signature and delegate to that. I'll put the full snippet (in Java) as a threaded reply to this message (BOOOO threads)
Copy code
static class Whatever {
  String time_zone;
  Metadata metadata;
}

static class Metadata {
  String foo;
}

static class Adapters {
  @FromJson Metadata nested(JsonReader reader, JsonAdapter<Metadata> nestedAdapter) throws IOException {
    String json = reader.nextString();
    return nestedAdapter.fromJson(json);
  }

  @ToJson void nested(JsonWriter writer, Metadata metadata, JsonAdapter<Metadata> nestedAdapter) throws IOException {
    String json = nestedAdapter.toJson(metadata);
    writer.value(json);
  }
}

@Test public void nested() throws IOException {
  Moshi moshi = new Moshi.Builder()
      .add(new Adapters())
      .build();
  JsonAdapter<Whatever> adapter = moshi.adapter(Whatever.class);

  Whatever whatever = adapter.fromJson(""
      + "{\n"
      + "  \"time_zone\": \"America/New_York\",\n"
      + "  \"metadata\": \"{\\\"foo\\\":\\\"bar\\\"}\"\n"
      + "}");
  assertThat(whatever.time_zone).isEqualTo("America/New_York");
  assertThat(whatever.metadata.foo).isEqualTo("bar");

  String json = adapter.toJson(whatever);
  assertThat(json).isEqualTo(""
      + "{\"metadata\":\"{\\\"foo\\\":\\\"bar\\\"}\",\"time_zone\":\"America/New_York\"}");
}
w
thanks jake - i’ll give that a shot
j
note that this will apply to all
Metadata
types. You may want to add a
@NestedJson
JsonQualifer to explicitly mark something as being nested... and in that case it's actually better to use a
JsonAdapter.Factory
because you can make it work for any type
w
cool, thanks again. my updated unit tests seem to be working great