【发布时间】:2016-09-25 12:04:03
【问题描述】:
各位开发者,你们好,
我在我的 Android 应用程序中使用来自 google 的 gson lib 苦苦挣扎。我正在尝试将对象列表序列化为 Json 字符串,但是没有运气。我的继承层次结构如下所示:
interface IFloorPlanPrimitive
abstract class FloorPlanPrimitiveBase implements IFloorPlanPrimitive
class Wall extends FloorPlanPrimitiveBase
class Mark extends FloorPlanPrimitiveBase
很简单。每个类都有一些字段。我在网上搜索了这个问题并添加了这个适配器类以方便序列化/反序列化。目前我无法序列化,所以让我们专注于此。
public class FloorPlanPrimitiveAdapter implements
JsonSerializer<FloorPlanPrimitiveBase>, JsonDeserializer<FloorPlanPrimitiveBase> {
@Override
public JsonElement serialize(FloorPlanPrimitiveBase src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = new JsonObject();
result.add("type", new JsonPrimitive(src.getClass().getSimpleName()));
result.add("properties", context.serialize(src, src.getClass()));
return result;
}
@Override
public FloorPlanPrimitiveBase deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
String type = jsonObject.get("type").getAsString();
JsonElement element = jsonObject.get("properties");
try {
final String packageName = IFloorPlanPrimitive.class.getPackage().getName();
return context.deserialize(element, Class.forName(packageName + '.' + type));
} catch (ClassNotFoundException cnfe) {
throw new JsonParseException("Unknown element type: " + type, cnfe);
}
}
}
这就是我使用它的方式:
public String getFloorPlanAsJSon() {
GsonBuilder gsonBilder = new GsonBuilder();
gsonBilder.registerTypeAdapter(FloorPlanPrimitiveBase.class, new FloorPlanPrimitiveAdapter());
Gson gson = gsonBilder.create();
List<IFloorPlanPrimitive> floorPlan = mRenderer.getFloorPlan();
String jsonString = gson.toJson(floorPlan);
return jsonString;
}
从一个简单的调试中我看到FloorPlanPrimitiveAdapter 的serialize 方法在序列化时没有被调用,因此我在Json 中没有得到那些“类型”和“属性”字段。相反,我得到了直接的 Json 字符串。我想这是由于类型不匹配。我要求序列化IFloorPlanPrimitive,而是传递实现此接口的FloorPlanPrimitiveBase。我的期望是它应该工作:)
谁能指出在这种情况下如何处理序列化和反序列化?如何克服这种“不匹配”?
提前谢谢你,
亲切的问候,格雷格。
【问题讨论】:
标签: android json serialization polymorphism