我想将我的代码从GSon迁移到MOSHI,以便获得OK库的常见底层用法的好处,因为我正在使用此工具还有OKHTTP和Retrofit。将HashMap的列表从/转换为JSON失败,使用Moshi 1.2.0
但是,这是GSON简单的任务似乎与MOSHI复杂:
我有一个包含对象列表的类。
而这些对象由字段名/值对组成 - 我将它实现为一个HashMap。在这个类中还有一些构造函数和方法,但对于JSON只有字段/值对是相关的。
精简到最低限度,我的JSON应该是这样的:
{"children":[{"f1":"v11","f2":"v12"},{"f1":"v21","f2":"v22"}]}
当我尝试这些类转换成JSON与MOSHI和背部,孩子们都是空的。
转换为JSON给
{"children":[{},{}]}
而且JSON字符串从上面的Class2的deserialisation给2个孩子,但孩子们都emppty。
在我真正的代码中,我的父对象也包含其他类的对象列表 - 这些类按预期工作。这里的问题似乎是我的孩子类从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());
}
}