这两天项目接近冒烟阶段,没时间作详细描述。将关键类列举如下:
序列化的Adapter:
/** * @author lanbo.xj * */ public class CarTypeAdapter implements JsonSerializer<Car> { private static Gson gson = new Gson(); @Override public JsonElement serialize(Car car, Type type, JsonSerializationContext context) { JsonObject jo = new JsonObject(); jo.add(car.getClass().getName(), gson.toJsonTree(car, car.getClass())); return jo; } }
反序列化的Adapter:
/** * @author lanbo.xj * */ public class CarListTypeAdapter implements JsonDeserializer<List<Car>> { @Override public List<Car> deserialize(JsonElement je, Type type, JsonDeserializationContext context) throws JsonParseException { List<Car> cars = new ArrayList<Car>(); JsonArray jsonArr = je.getAsJsonArray(); for (Iterator<JsonElement> iter = jsonArr.iterator(); iter.hasNext();) { JsonObject jo = (JsonObject) iter.next(); for (Entry<String, JsonElement> entry : jo.entrySet()) { String className = entry.getKey(); try { @SuppressWarnings("rawtypes") Class clazz = null; clazz = Class.forName(className); System.out.println(clazz.getName()); Car car = context.deserialize(entry.getValue(), clazz); cars.add(car); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } return cars; } }
测试类:
public class GsonTest { public static void main(String[] args) { JeepCar car1 = new JeepCar(); car1.setPrice(1000); car1.setSpeed(200); MotorCar car2 = new MotorCar(); car2.setPrice(2000); car2.setYear(1999); List<Car> cars = new ArrayList<Car>(); cars.add(car1); cars.add(car2); GsonBuilder gb = new GsonBuilder().serializeNulls(); Type baseType = new TypeToken<List<Car>>(){}.getType(); gb.registerTypeAdapter(baseType, new CarListTypeAdapter()); gb.registerTypeAdapter(JeepCar.class, new CarTypeAdapter()); gb.registerTypeAdapter(MotorCar.class, new CarTypeAdapter()); Gson gson = gb.create(); String str = gson.toJson(cars); System.out.println(str); List<Car> cars3 = gson.fromJson(str, baseType); System.out.println(((JeepCar)cars3.get(0)).getSpeed()); } }