Gsonを使って、Serializableじゃないフィールドを持つクラスをパースしようとするとエラーになります。
問題
パースしたいModel。
public class Sample {
@SerializedName("title")
private String title;
private NotSerializableObject object;
}
パースするコード。
new Gson().fromJson(sampleJson, Sample.class);
出力されるエラー。
java.lang.AssertionError
at com.google.gson.internal.bind.TypeAdapters$EnumTypeAdapter.<init>(SourceFile:733)
at com.google.gson.internal.bind.TypeAdapters$26.create(SourceFile:762)
at com.google.gson.Gson.getAdapter(SourceFile:356)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(SourceFile:82)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(SourceFile:81)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(SourceFile:118)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(SourceFile:72)
解決
Serializableじゃないフィールドを持つクラスをパースするときは、そのフィールドにtransient
をつけます。
private transient NotSerializableObject object;
ただし、transientを使うとそのフィールドはSerializeの対象から外れてしまうので注意が必要かもしれません。