Converter { static Type list(Type searchFor, String... roots) { return new CompositeType(new ListTypeImpl(searchFor), roots); } Converter(Moshi moshi); Moshi moshi(); @SuppressWarnings("unchecked") // Type matching is the caller's responsibility. R convertFromBody(Type type, ResponseBody body); RequestBody convertToBody(Type type, B body); @SuppressWarnings("unchecked") JsonAdapter<T> findAdapter(Type type);  }
@Test public void listObject() throws Exception { Type type = Converter.list(TestData.class, "content"); List<TestData> fromJson = fromJson(type, "{\n" + " \"content\": [\n" + " {\n" + " \"str\": \"zero\",\n" + " \"val\": 0\n" + " },\n" + " {\n" + " \"str\": \"one\",\n" + " \"val\": 1\n" + " },\n" + " {\n" + " \"str\": \"two\",\n" + " \"val\": 2\n" + " }\n" + " ]\n" + '}'); assertThat(fromJson).isNotNull(); assertThat(fromJson).hasSize(3); assertThat(fromJson.get(0).str).isEqualTo("zero"); assertThat(fromJson.get(1).str).isEqualTo("one"); assertThat(fromJson.get(2).str).isEqualTo("two"); assertThat(fromJson.get(0).val).isEqualTo(0); assertThat(fromJson.get(1).val).isEqualTo(1); assertThat(fromJson.get(2).val).isEqualTo(2); String toJson = toJson(type, fromJson); assertThat(toJson).isEqualTo("{\"content\":[" + "{\"str\":\"zero\",\"val\":0}," + "{\"str\":\"one\",\"val\":1}," + "{\"str\":\"two\",\"val\":2}]" + '}'); }
@Test public void listObjectWrongRoots() throws Exception { Type type = Converter.list(TestData.class, "asdasdasd"); try { fromJson(type, "{\n" + " \"content\": []\n" + '}'); fail(); } catch (IOException ioe) { assertThat(ioe).hasMessage("Json does not match expected structure for roots [asdasdasd]."); } }
@Test(expected = JsonDataException.class) public void listObjectWithoutRoot() throws Exception { Type type = Converter.list(TestData.class); fromJson(type, "{\n" + " \"content\": []\n" + '}'); }
@Test(expected = JsonDataException.class) public void listObjectMultipleRoots() throws Exception { Type type = Converter.list(TestData.class, "users", "companies"); fromJson(type, "{\n" + " \"users\": [\n" + " {\n" + " \"companies\": [\n" + " {\n" + " \"str\": \"company1\",\n" + " \"val\": 1\n" + " },\n" + " {\n" + " \"str\": \"company1\",\n" + " \"val\": 1\n" + " },\n" + " {\n" + " \"str\": \"company1\",\n" + " \"val\": 1\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + '}'); }