Skip to content

Instantly share code, notes, and snippets.

@jizhang
Created January 26, 2015 02:53
Show Gist options
  • Save jizhang/6150bef9032322a80ffe to your computer and use it in GitHub Desktop.
Save jizhang/6150bef9032322a80ffe to your computer and use it in GitHub Desktop.
json4s opt methods
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