jw
08/12/2021, 1:45 PMjw
08/12/2021, 1:45 PMstatic 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\"}");
}
William Reed
08/12/2021, 1:59 PMjw
08/12/2021, 2:08 PMMetadata
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 typeWilliam Reed
08/12/2021, 3:09 PM