我想将我的代码从 GSon 迁移到 MOSHI 以获得 OK-Libraries 的常见底层用法的好处,因为我也在使用 OKHTTP 和 Retrofit。
但是对于 Gson 来说很简单的任务,对于 MOSHI 来说似乎很复杂:
我有一个包含对象列表的类。
这些对象由字段名/值对组成——我将其实现为 HashMap。在这个类中有更多的构造函数和方法,但对于 JSON,只有字段/值对是相关的。
精简到最低限度,我的 JSON 应该如下所示:
{"children":[{"f1":"v11","f2":"v12"},{"f1":"v21","f2":"v22"}]}
当我尝试使用 MOSHI 将这些类转换为 JSON 并返回时,孩子是空的。
转换为 JSON 给出
{"children":[{},{}]}
并且从上面到 Class2 的 json-string 的反序列化给出了 2 个孩子,但孩子是空的。
在我的真实代码中,我的父对象还包含其他类的对象列表——这些类按预期工作。这里的问题似乎是我的子类是从 HashMap 扩展而来的。
使用 Gson,一切都按预期工作。
这是单元测试,我写来测试行为。
public class Test_Moshi {
private final Moshi moshi = new Moshi.Builder().build();
private static class Class1 extends HashMap<String, Object> {
//Some Constructors and methods omitted for the test.
//Relevant for the serilisation to JSON are only the keys and values in the map.
}
private static class Class2 {
List<Class1> children = new ArrayList<>();
}
@Test public void test1() {
Class1 child;
Class2 parent = new Class2();
child = new Class1();
child.put("f1", "v11");
child.put("f2", "v12");
parent.children.add(child);
child = new Class1();
child.put("f1", "v21");
child.put("f2", "v22");
parent.children.add(child);
String json_gson = new Gson().toJson(parent);
String json_moshi = moshi.adapter(Class2.class).toJson(parent);
assertEquals(json_gson, json_moshi);
}
@Test public void test2() throws IOException {
String json = "{\"children\":[{\"f1\":\"v11\",\"f2\":\"v12\"},{\"f1\":\"v21\",\"f2\":\"v22\"}]}";
Class2 class2 = moshi.adapter(Class2.class).fromJson(json);
assertEquals(2, class2.children.size());
assertEquals("Child 1 contains expected number of fields", 2, class2.children.get(0).size());
assertEquals("Child 2 contains expected number of fields", 2, class2.children.get(1).size());
}
}