Converter { static Type single(Type searchFor, String... roots) { return new CompositeType(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 singleObjects() throws Exception { Type type = Converter.single(TestData.class); TestData fromJson = fromJson(type, "{\n" + " \"str\": \"test\",\n" + " \"val\": 42\n" + '}'); assertThat(fromJson).isNotNull(); assertThat(fromJson.str).isEqualTo("test"); assertThat(fromJson.val).isEqualTo(42); String toJson = toJson(type, fromJson); assertThat(toJson).isEqualTo("{\"str\":\"test\",\"val\":42}"); }
@Test public void singleObjectsWithRoots() throws Exception { Type type = Converter.single(TestData.class, "findMe"); TestData fromJson = fromJson(type, "{\n" + " \"findMe\": {\n" + " \"str\": \"test1\",\n" + " \"val\": 43\n" + " }\n" + '}'); assertThat(fromJson).isNotNull(); assertThat(fromJson.str).isEqualTo("test1"); assertThat(fromJson.val).isEqualTo(43); String toJson = toJson(type, fromJson); assertThat(toJson).isEqualTo("{\"findMe\":{\"str\":\"test1\",\"val\":43}}"); }
@Test public void singleObjectsWithMultipleRoots() throws Exception { Type type = Converter.single(TestData.class, "findMe", "andMe"); TestData fromJson = fromJson(type, "{\n" + " \"findMe\": {\n" + " \"andMe\": {\n" + " \"str\": \"test2\",\n" + " \"val\": 44\n" + " }\n" + " }\n" + '}'); assertThat(fromJson).isNotNull(); assertThat(fromJson.str).isEqualTo("test2"); assertThat(fromJson.val).isEqualTo(44); String toJson = toJson(type, fromJson); assertThat(toJson).isEqualTo("{\"findMe\":{\"andMe\":{\"str\":\"test2\",\"val\":44}}}"); }
@Test public void singleObjectsWithNullObjectInside() throws Exception { Type type = Converter.single(TestData.class, "findMe", "andMe"); TestData fromJson = fromJson(type, "{\n" + " \"findMe\": {\n" + " \"andMe\": {\n" + " }\n" + " }\n" + '}'); assertThat(fromJson).isNotNull(); assertThat(fromJson.str).isNullOrEmpty(); assertThat(fromJson.val).isEqualTo(0); String toJson = toJson(Converter.single(Object.class, "findMe", "andMe"), new Object()); assertThat(toJson).isEqualTo("{\"findMe\":{\"andMe\":{}}}"); }
@Test public void singleObjectsWithRootsNull() throws Exception { Type type = Converter.single(TestData.class, (String[]) null); TestData fromJson = fromJson(type, "{\n" + " \"findMe\": {\n" + " \"andMe\": {\n" + " }\n" + " }\n" + '}'); assertThat(fromJson).isNotNull(); assertThat(fromJson.str).isNullOrEmpty(); assertThat(fromJson.val).isEqualTo(0); String toJson = toJson(type, fromJson); assertThat(toJson).isEqualTo("{\"val\":0}"); }
@Test public void objectWithNull() throws Exception { Type type = Converter.single(TestData.class, "root"); TestData fromJson = fromJson(type, "{\n" + " \"root\": null\n" + '}'); assertThat(fromJson).isNull(); }