Required fields in scala map -
i have jsonmap : map[string , any] , extracting 3 required field map
//case class exception handling case class parserexception(message: string) extends exception(message) val id = jsonmap.getorelse("id", throw parserexception("id required.")) val type = jsonmap.getorelse("type", throw parserexception("type required.")) val location = jsonmap.getorelse("location", throw parserexception("location required."))
if json don't have required value exception raised.is there better way in scala implement required field extract ?
expected : if field missing json , code should throw exception..if mandatory fields available program flow should move next step.
lift map partial function missing keys mapped none
, defined keys some(value)
; example,
scala> val m = map("id" -> 1, "loc" -> 2) m: scala.collection.immutable.map[string,int] = map(id -> 1, loc -> 2) scala> m.lift("id") res0: option[int] = some(1) scala> m.lift("missing") res1: option[int] = none
note lift once, viz. val ml = m.lift
, query many, e.g. ml("id")
Comments
Post a Comment