Created
January 26, 2015 02:53
-
-
Save jizhang/6150bef9032322a80ffe to your computer and use it in GitHub Desktop.
json4s opt methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.json4s._ | |
object JsonUtils { | |
implicit class AugmentJValue(val jvalue: JValue) { | |
implicit val formats = DefaultFormats | |
def getString(key: String): String = { | |
Option((jvalue \ key).extract[String]).get | |
} | |
def optString(key: String, default: String = ""): String = { | |
try { | |
getString(key) | |
} catch { | |
case _: Exception => default | |
} | |
} | |
def getInt(key: String): Int = { | |
(jvalue \ key).extractOpt[Int] match { | |
case Some(result) => result | |
case None => (jvalue \ key).extract[String].toInt | |
} | |
} | |
def optInt(key: String, default: Int = 0): Int = { | |
try { | |
getInt(key) | |
} catch { | |
case _: Exception => default | |
} | |
} | |
def getLong(key: String): Long = { | |
(jvalue \ key).extractOpt[Long] match { | |
case Some(result) => result | |
case None => (jvalue \ key).extract[String].toLong | |
} | |
} | |
def optLong(key: String, default: Long = 0): Long = { | |
try { | |
getLong(key) | |
} catch { | |
case _: Exception => default | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment