Issue
I am following this ROOM tutorial and at some point we need to create Type Converters for ROOM. GSON is being used to parse to and from JSON.
To achieve this we first create this general interface which contains 2 functions to get an object from a JSON String or to parse an object to JSON String. This is so in case you decide to switch to a different library to parse JSON Strings.
interface JsonParser {
//takes the actual JSON String and return an object of our type
fun <T> fromJson(json: String, type: Type): T?
//takes our object and return JSON String
fun <T> toJson(obj: T, type: Type): String?
}
The next step is to create the implementation of the above interface where GSON is used.
//JsonParser implementation
class GsonParser (private val gson: Gson):JsonParser {
override fun <T> fromJson(json: String, type: Type): T? {
return gson.fromJson(json,type)
}
override fun <T> toJson(obj: T, type: Type): String? {
return gson.toJson(obj,type)
}
}
For my case I am looking to do the same but with Moshi. Unfortunately Moshi doesn't have toJson()
or fromJson()
methods.
Have tried looking for Moshi methods equivalent GSON's toJson()
and fromJson()
but I am not getting anything. How can I go about this?
Solution
I went through the Moshi Documentations provided by @CommonsWare on his above comment"
The solution is to first add dependencies for Moshi/Retrofit
to your project.
// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'
//Moshi Library Dependencies - Core Moshi JSON Library and Moshi's Kotlin support and converter factory
implementation "com.squareup.moshi:moshi:1.12.0"
implementation "com.squareup.moshi:moshi-kotlin:1.12.0"
Then create a class name MoshiParser
that implements JsonParser Interface and initialize Moshi
. For Moshi's annotations to work properly with Kotlin, you just add the KotlinJsonAdapterFactory
on Moshi Builder.
The next item is to use Moshi's JsonAdapter which takes a generic type of <T>
. JsonAdpater provides JsonAdpater.toJson()
and JsonAdapter.fromJson()
.
class MoshiParser() : JsonParser {
//initialize Moshi
private val moshi: Moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
override fun <T> fromJson(json: String, type: Type): T? {
//use jsonAdapter<T> for generic adapter
val jsonAdapter: JsonAdapter<T> = moshi.adapter(type)
return jsonAdapter.fromJson(json)
}
override fun <T> toJson(obj: T, type: Type): String? {
//use jsonAdapter<T> for generic adapter
val jsonAdapter: JsonAdapter<T> = moshi.adapter(type)
return jsonAdapter.toJson(obj)
}
}
Answered By - Tonnie
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.