父类
package inheritance.test2; import java.util.Map; public class Model { private String field1; private String field2; private Map<String, String> infoMap; public String getField2() { return field2; } public void setField2(String field2) { this.field2 = field2; } public String getField1() { return field1; } public void setField1(String field1) { this.field1 = field1; } public Map<String, String> getInfoMap() { return infoMap; } public void setInfoMap(Map<String, String> infoMap) { this.infoMap = infoMap; } }
子类
package inheritance.test2; public class DetailModel extends Model { private String field3; private String field4; public String getField3() { return field3; } public void setField3(String field3) { this.field3 = field3; } public String getField4() { return field4; } public void setField4(String field4) { this.field4 = field4; } }
测试类:
package inheritance.test2; import com.google.gson.Gson; import org.junit.Assert; import java.util.HashMap; import java.util.Map; public class Test { @org.junit.Test public void testGsonInheritance() { DetailModel dm = new DetailModel(); dm.setField1("field1"); dm.setField2("field2"); dm.setField3("field3"); dm.setField4("field4"); Map<String, String> im = new HashMap<String, String>(); im.put("key1","value1"); im.put("key2","value2"); im.put("key3","value3"); dm.setInfoMap(im); String str = new Gson().toJson(dm); System.out.println(str); Model model = new Gson().fromJson(str, Model.class); Assert.assertTrue(model.getField1().equals(dm.getField1())); Assert.assertTrue(model.getField2().equals(dm.getField2())); Map<String, String> map = model.getInfoMap(); Assert.assertEquals(map.size(), 3); Assert.assertNotNull(map.get("key1")); Assert.assertNotNull(map.get("key2")); dm.setInfoMap(null); str = new Gson().toJson(dm); model = new Gson().fromJson(str, Model.class); map = model.getInfoMap(); Assert.assertNull(map); } }
总结
1. 子类序列化为JSON串,JSON串反序列化为父类,相应的字段可以完成反序列化,其它字段自动抛弃,这符合面向对象的特性,子类造型为父类,通过父类可以访问父类提供的数据访问方法,子类自己的数据不能访问
2. 反序列化时,如果POJO的字段在JSON串中不存在,那么POJO的这个字段为null
3. 这个例子具有一般性,更常见的场景,从别的系统获取JSON数据串,但是JSON串内容很丰富,有些字段不是自身的系统所需要的,可以定义一个简单的POJO,在反序列化时,将感兴趣的字段和数据反序列化到POJO中,POJO只包含自己感兴趣的内容