0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Not Serializableなフィールドを持つオブジェクトをGsonでパースする

Posted at

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の対象から外れてしまうので注意が必要かもしれません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?