Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] android – How to parse retrofit json response to object model with Moshi

Posted on November 11, 2022 By

Solution 1 :

If you want to use Moshi with Kotlin reflection you have to don’t forget to add KotlinJsonAdapterFactory. This will work fine I guess:

val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()
val jsonAdapter = moshi.adapter(BaseValidation::class.java)
val baseValidation = jsonAdapter.fromJson(response.errorBody()!!.charStream().toString())!!

also, you can remove @JsonClass annotation from your classes. It’s not needed for while you are using reflection.

Problem :

Retrofit Instance:

    fun getMoshi() : Moshi{
        return Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .build()
    }


    fun retrofit(baseUrl: String): Retrofit = Retrofit.Builder()
        .client(getClient())
        .baseUrl(baseUrl)
        .addConverterFactory(MoshiConverterFactory.create(getMoshi()).asLenient())
        .build()

}

BaseValidation model:

    @JsonClass(generateAdapter = true)
    data class BaseValidation (
        val status : String,
        val data : List<Data>
    )

response parsing:

   val type: Type = Types.newParameterizedType(String::class.java, Data::class.java)
    val moshi = Moshi.Builder().build()
    val jsonAdapter: JsonAdapter<Map<String,Data>> = moshi.adapter(type)
    val baseValidation = jsonAdapter.fromJson(response.errorBody()!!.charStream().toString())!!

results in:

Platform class java.lang.String in java.lang.String<com.example.vow.data_remote.model.create.response.validation.Data> requires explicit JsonAdapter to be registered

I am new to Moshi and kind of confused how to parse correctly, I’ve managed to achieve the result with gson using code below, but I want to learn how it’s done with Moshi:

val gson = Gson()
val type = object : TypeToken<BaseValidation>() {}.type
var errorResponse: BaseValidation? = gson.fromJson(response.errorBody()!!.charStream(), type)

is the Type below defined correctly?

val type: Type = Types.newParameterizedType(String::class.java, Data::class.java)

UPDATE

val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val jsonAdapter: JsonAdapter<BaseValidation> = moshi.adapter(BaseValidation::class.java).lenient()
val baseValidation = jsonAdapter.fromJson(response.errorBody()!!.charStream().toString())!!

returns

com.squareup.moshi.JsonEncodingException: Use JsonReader.setLenient(true) to accept malformed JSON at path $

When moshi set to lenient() by

moshi.adapter(BaseValidation::class.java).lenient()

i get

Expected BEGIN_OBJECT but was STRING at path $

OkHttp response is

{
    "status": "validation",
    "data": [
        {
            "type": "Email",
            "code": 3000,
            "field": "User.contact.email",
            "message": "Email is invalid"
        }
    ]
}

SOLUTION

maybe it will help someone in the future

 response.errorBody()!!.charStream().toString()

instead should be

response.errorBody()?.source()

Comments

Comment posted by chitgoks

I am actually curious if it’s possible to not create a data class that will retrieve status and data properties but instead, access the data array property right away. the status in my case is always success, so there’s no point creating a data class that will hold the status and data list. thoughts?

READ  [FIXED] android - Using Retrofit 2 in Intent Service class
Powered by Inline Related Posts

Comment posted by Juan José Melero Gómez

I see you’re using Retrofit with

Android Tags:android, kotlin, moshi, retrofit, retrofit2

Post navigation

Previous Post: [FIXED] java – Access Binding Adapters in multi module project
Next Post: [FIXED] java – Changing value in on item also changes in another item – RecyclerView Android

Related Posts

[FIXED] javascript – Error on a Specific Line Number – Android Studio Android
[FIXED] gradle – After Android Studio update. Could not parse POM, Could not resolve all files for configuration ‘:app:_internal_aapt2_binary’ Android
[FIXED] android – How to delete an app’s data when app is deleted Android
[FIXED] java – Create a bump effect for a bottom sheet android studio Android
[FIXED] android – How to update progressbar at 10 percent increments? Android
[FIXED] Test app for samsung smart tv on emulator Android

Archives

  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • Can Vicks humidifier be used without filter?
  • What color is Spanish green?
  • How old is Jamie in The War That Saved My Life?
  • When should I use scalp massager for hair growth?
  • Can I put polyurethane over liming wax?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme