๐์ฐธ๊ณ ์๋ฃ
๐์ฐธ๊ณ ์๋ฃ: Moshi ๊ด๋ จ Exception error | Inflearn
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
object TourItemJsonConverter {
fun toJson(tourItem: TourItem): String {
val serializedPair = tourItem.getContentTypeId() to Gson().toJson(tourItem)
return Gson().toJson(serializedPair)
}
fun fromJson(json: String): TourItem {
val type = object : TypeToken<Pair<String, String>>() {}.type
val serializedPair: Pair<String, String> = Gson().fromJson(json, type)
val tourItemType = when (serializedPair.first) {
TourContentTypeId.TOURIST_DESTINATION.contentTypeId -> {
object : TypeToken<TourItem.TouristDestination>() {}.type
}
TourContentTypeId.CULTURAL_FACILITIES.contentTypeId -> {
object : TypeToken<TourItem.CulturalFacilities>() {}.type
}
TourContentTypeId.RESTAURANT.contentTypeId -> {
object : TypeToken<TourItem.Restaurant>() {}.type
}
TourContentTypeId.LEISURE_SPORTS.contentTypeId -> {
object : TypeToken<TourItem.LeisureSports>() {}.type
}
TourContentTypeId.EVENT_PERFORMANCE_FESTIVAL.contentTypeId -> {
object : TypeToken<TourItem.EventPerformanceFestival>() {}.type
}
else -> {
object : TypeToken<TourItem.TouristDestination>() {}.type
}
}
return Gson().fromJson(serializedPair.second, tourItemType)
}
}
plugins {
id("com.google.devtools.ksp").version("1.6.10-1.0.4")
}
dependencies {
implementation("com.squareup.moshi:moshi:1.15.0")
implementation("com.squareup.moshi:moshi-kotlin:1.14.0")
ksp ("com.squareup.moshi:moshi-kotlin-codegen:1.8.0")
implementation("com.squareup.moshi:moshi-adapters:1.9.2")
}
@JsonClass(generateAdapter = true)
์ ๋
ธํ
์ด์
์ถ๊ฐimport android.util.Log
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.Moshi
import com.squareup.moshi.adapters.PolymorphicJsonAdapterFactory
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
object TourItemJsonConverter {
private val TAG = "TourItemJsonConverter"
private val moshi = Moshi.Builder()
.add(
PolymorphicJsonAdapterFactory.of(TourItem::class.java, "tour_item_type")
.withSubtype(TourItem.TouristDestination::class.java, "tourist_attraction")
.withSubtype(TourItem.CulturalFacilities::class.java, "cultural_facilities")
.withSubtype(TourItem.Restaurant::class.java, "restaurant")
.withSubtype(TourItem.LeisureSports::class.java, "leisure_sports")
.withSubtype(TourItem.EventPerformanceFestival::class.java, "event_performance_festival")
)
.add(KotlinJsonAdapterFactory())
.build()
fun toJson(tourItem: TourItem): String {
Log.d(TAG, "toJson, TourItem:${tourItem.getTitle()}")
return try{
moshi.adapter(TourItem::class.java).toJson(tourItem)
}catch (e:JsonDataException){
e.printStackTrace()
""
}
}
fun fromJson(json: String): TourItem? {
Log.d(TAG, "fromJson, json: ${json}")
return try {
moshi.adapter(TourItem::class.java).fromJson(json)
}catch (e:JsonDataException){
e.printStackTrace()
null
}
}
}