Home > Enterprise >  Deserialize only few properties
Deserialize only few properties

Time:10-28

When using Kotlin with Moshi to parse an api response, I receive quite a large JSON object back.

However, all of the examples I see, they create an object to pass to the adapter() that includes all of the properties. However, I only need 4-5 of them.

How can I accomplish this? Currently this doesn't work:

val moshi = Moshi.Builder().build()

val jsonAdapter = moshi.adapter(OnLoadUser::class.java)

val onl oadUser = jsonAdapter.nullSafe().lenient().fromJson(data)

It gives this error:

E/EventThread: Task threw exception
    java.lang.IllegalArgumentException: Cannot serialize Kotlin type com.biz.app.models.OnLoadUser. Reflective serialization of Kotlin classes without using kotlin-reflect has undefined and unexpected behavior. Please use KotlinJsonAdapterFactory from the moshi-kotlin artifact or use code gen from the moshi-kotlin-codegen artifact.
        at com.squareup.moshi.ClassJsonAdapter$1.create(ClassJsonAdapter.java:97)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:145)
        at com.squareup.moshi.Moshi.adapter(Moshi.java:105)

It's really a large JSON object, and I only need 4 properties:

{
name: 'John Doe',
email: '[email protected]',
token: 'QWERTY',
guid: '1234-5678-ASDF-9012'
...
}

CodePudding user response:

Annotate properties that you want to skip with @Transient, they will be omitted by moshi.

CodePudding user response:

The issue was that I wasn't using the KotlinJsonAdapterFactory(). I had to add it:

val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()

And also in the gradle.build, so that it was available as an import:

implementation("com.squareup.moshi:moshi-kotlin:1.12.0")

After doing this, it could properly parse the JSON data with a partial Kotlin object.

  • Related