I am using Play JsPath
val jsonrecord = "{\"id\":111,\"zip\":\"123\"}"
case class record(id: Int, name: Int)
def validZip(name:String) = name.matches("""^[0-9]*$""")
def jsonextraction(json: JsValue): record = {
implicit val jsonread: Reads[record] = (
(JsPath \ "id").read[Int] and
(JsPath \ "zip").read[String](validZip)
) (record.apply _)
val result = json.as[record]
result
}
how to convert name
field string to Int
json input field is zip is quotes like string "123".
I trying to remove quotes and make it Integer ,
checking empty values it should not be empty , if it is empty trying to throw exception like bad record
You can just map to an integer like so:
(JsPath \ "zip").read[String].map(_.toInt)
Here is a minimal working example:
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.libs.json.Reads._
case class record(id: Int, name: Int)
object record {
implicit val jsonread: Reads[record] = (
(JsPath \ "id").read[Int] and
(JsPath \ "zip").read[String](pattern("""^[0-9]*$""".r)).map(_.toInt)
)(record.apply _)
}
object PlayJson extends App {
val jsonrecord = """{ "id": 111, "zip": "123" }"""
println(Json.parse(jsonrecord).as[record])
}