良い一日私の仲間の開発者と呼ばれていません。私はJsonの文字列にオブジェクトのリストをシリアル化しようとしているが、運がない。私の継承階層は次のようになります。アンドロイドgson AbstractAdapter.serializeは、(ポリモーフィックシリアライズ)
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);
}
}
}
そして、これは私がそれを使用する方法です:私はシリアライズので、私はそれらの「タイプ」を取得していないときFloorPlanPrimitiveAdapter
のserialize
メソッドが呼び出されていないことがわかり、簡単なデバッグから
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;
}
Jsonの "properties"フィールドを使用します。代わりに、私はストレートフォワードJsonの文字列を取得します。これはタイプの不一致によるものだと思います。私はIFloorPlanPrimitive
をシリアル化するように求めていますが、代わりにこのインターフェイスを実装するFloorPlanPrimitiveBase
を渡します。私の期待は、それが動作するはずでした:)
誰もこの状況でシリアル化とデシリアライズを処理する方法を指摘できますか?その "ミスマッチ"を克服する方法は?
ありがとうございました。
親切、グレッグ。