Skip to content

Commit

Permalink
Add tryParseJson utility method (#1117)
Browse files Browse the repository at this point in the history
* Add tryParseJson utility method

* formatting
  • Loading branch information
atavism authored Jul 4, 2024
1 parent f0be62b commit 8b99194
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package org.getlantern.lantern.util
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.getlantern.mobilesdk.Logger

object JsonUtil {

Expand All @@ -20,4 +21,13 @@ object JsonUtil {
inline fun <reified T> toJson(obj: T): String {
return json.encodeToString(obj)
}
}

inline fun <reified T> tryParseJson(s: String?): T? {
return try {
fromJson(s ?: return null)
} catch (e: Exception) {
Logger.error("JsonUtil", "Unable to parse JSON", e)
null
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,10 @@ open class LanternHttpClient : HttpClient() {

override fun onSuccess(response: Response?, result: JsonObject?) {
result?.let {
val user: ProUser = JsonUtil.fromJson<ProUser>(result.toString())
cb.onSuccess(response!!, user)
val user: ProUser? = JsonUtil.tryParseJson<ProUser?>(result.toString())
user?.let {
cb.onSuccess(response!!, user)
}
}
}
})
Expand All @@ -91,27 +93,8 @@ open class LanternHttpClient : HttpClient() {
) {
Logger.debug(TAG, "JSON response" + result.toString())
result?.let {
try {
val user = JsonUtil.fromJson<ProUser>(result.toString())
Logger.debug(TAG, "User ID is ${user.userId}")
cb.onSuccess(response!!, user)
} catch (e: SerializationException) {
// If for some reason we get error return user with basic string
Logger.error(TAG, "Unable to parse user from JSON", e)
val userId = result.get("userId").asLong
val token = result.get("token").asString
val referral = result.get("referral").asString
val email = result.get("email").asString
val userStatus = result.get("userStatus").asString
val userLevel = result.get("userLevel").asString
val user = ProUser(
userId, token, referral, email, userStatus, "", "en_us", "", 0L,
mutableListOf(), userLevel
)
cb.onSuccess(response!!, user)

}

var user: ProUser? = JsonUtil.tryParseJson<ProUser?>(result.toString())
user?.let { cb.onSuccess(response!!, it) }
}
}
},
Expand Down

0 comments on commit 8b99194

Please sign in to comment.