1

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

1 Answer 1

2

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])
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, Its working but its not checking empty values,
I trying to check empty values also for the zip field also
@Nathon Replace * with + in the regex like so: """^[0-9]+$""".r

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.