11package com.runnect.runnect.data.network.interceptor
22
3- import com.google.gson.Gson
4- import com.google.gson.JsonElement
5- import com.google.gson.JsonObject
6- import com.google.gson.JsonParseException
7- import com.google.gson.JsonSyntaxException
8- import com.runnect.runnect.data.dto.response.base.BaseResponse
3+ import kotlinx.serialization.json.Json
4+ import kotlinx.serialization.json.JsonObject
5+ import kotlinx.serialization.json.jsonObject
96import okhttp3.Interceptor
107import okhttp3.MediaType.Companion.toMediaTypeOrNull
118import okhttp3.Response
@@ -18,14 +15,14 @@ import timber.log.Timber
1815 */
1916class ResponseInterceptor : Interceptor {
2017
21- private val gson = Gson ()
18+ private val json = Json { ignoreUnknownKeys = true }
2219
2320 override fun intercept (chain : Interceptor .Chain ): Response {
2421 val originalResponse = chain.proceed(chain.request())
2522 if (! originalResponse.isSuccessful) return originalResponse
2623
2724 val bodyString = originalResponse.peekBody(Long .MAX_VALUE ).string()
28- val newResponseBodyString = jsonToBaseResponse (bodyString)?.let {
25+ val newResponseBodyString = extractData (bodyString)?.let {
2926 it.toResponseBody(" application/json" .toMediaTypeOrNull())
3027 } ? : return originalResponse
3128
@@ -42,26 +39,18 @@ class ResponseInterceptor : Interceptor {
4239 }
4340 }
4441
45- private fun jsonToBaseResponse (body : String ): String? {
42+ private fun extractData (body : String ): String? {
4643 return try {
47- val jsonElement: JsonElement = gson.fromJson(body, JsonElement ::class .java)
48- if (! isBaseResponse(jsonElement.asJsonObject)) {
49- return null
50- }
51-
52- val baseResponse = gson.fromJson(body, BaseResponse ::class .java)
53- gson.toJson(baseResponse.data)
54- } catch (e: JsonSyntaxException ) {
55- null // JSON 구문 분석 오류 발생 시 원래 형식을 반환
56- } catch (e: JsonParseException ) {
57- null // JSON 파싱 오류 발생 시 원래 형식을 반환
44+ val jsonObject = json.parseToJsonElement(body).jsonObject
45+ if (! isBaseResponse(jsonObject)) return null
46+ jsonObject[" data" ].toString()
5847 } catch (e: Exception ) {
59- null // 기타 예외 발생 시 원래 형식을 반환
48+ null
6049 }
6150 }
6251
6352 private fun isBaseResponse (jsonObject : JsonObject ): Boolean {
6453 val requiredFields = listOf (" status" , " success" , " message" , " data" )
65- return requiredFields.all { jsonObject.has(it) }
54+ return requiredFields.all { it in jsonObject }
6655 }
6756}
0 commit comments