如何在 Scala 的 Json Parser 中将 String 更改为 Int

How to change String to Int in Json Parser in scala

我正在使用 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 
}

如何将name字段字符串转换为Int json 输入字段是 zip 是引号,如字符串“123”。

我试图删除引号并将其设为整数,

检查空值它不应该是空的,如果它是空的试图抛出像坏记录这样的异常

您可以像这样映射到一个整数:

(JsPath \ "zip").read[String].map(_.toInt)

这是一个最小的工作示例:

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])
}