Search code examples
androidkotlingsonmoshi

Moshi equivalent to Gson.toJson


I'm new to Moshi and I was thinking to implement it to replace my Gson lib. Can't figure out how exactly I can convert a model class into a string in JSON format.

My model is UiGeneralCategory

I have this example but I think I'm a little overburned because something doesn't line up.

enter image description here

ok,

val jsonAdapter: JsonAdapter = moshi.adapter(UiGeneralCategory::class.java)

works, now i have to replace all the ArrayLists in models and test it


Solution

  • Ok, so here is my class for toJson/fromJson conversion (with generic object), It uses just one instance of the Moshi builder for optimization (from what I have seen is something like 400-500 millis)

    import android.util.Log
    import com.squareup.moshi.JsonAdapter
    import com.squareup.moshi.Moshi
    import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
    import java.lang.reflect.Type
    
    class MoshiHelper {
    
    private var mMoshiInstance: Moshi = getMoshi()
    
    private fun getMoshi(): Moshi {
        Log.d("testMoshiInstance112", "initialized ")
        return Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .build()
    }
    
    companion object {
        private var mInstance: MoshiHelper? = null
    
        fun getInstance(): MoshiHelper {
            if (mInstance == null) {
                mInstance = MoshiHelper()
            }
            return mInstance!!
        }
    
    }
    
    
    fun <T> moshiFromJson(json: String, type: Type): T {
        //use jsonAdapter<T> for generic adapter
        val jsonAdapter: JsonAdapter<T> = mMoshiInstance.adapter(type)
        return jsonAdapter.fromJson(json)!!
    }
    
    fun <T> moshiToJson(obj: T, type: Type): String {
        //use jsonAdapter<T> for generic adapter
        val jsonAdapter: JsonAdapter<T> = mMoshiInstance.adapter(type)
    
        return jsonAdapter.toJson(obj)
    }
    
    }
    

    And the usage:

    var mMoshiHelper = MoshiHelper.getInstance()
    
    var mPayload: String = mMoshiHelper.moshiToJson(mUiLocalModel, UiMyLocalModel::class.java)
    
    var mUiLocalModel: UiMyLocalModel = mMoshiHelper.moshiFromJson(mPayload, UiMyLocalModel::class.java)