scalaオブジェクトJsonとJsonオブジェクトの2つの方法

2685 ワード

直接本題に入る
import play.api.libs.functional.syntax._
import org.json4s.native.Serialization.read
import play.api.libs.functional.syntax.unlift
import play.api.libs.json.{JsPath, Json, Reads, Writes}

/**
  * Created by zmm on 2019/1/31
  */

case class FilterData(var id: Option[Int], publisherId: Int, subId: String, minPercentage: Byte, maxPercentage: Byte, var updateTime: Option[Int], status: Byte) {}

object JsonUtil {

  implicit val filterDataReads: Reads[FilterData] = (
    (JsPath \ "id").readNullable[Int] and
      (JsPath \ "publisher_id").read[Int] and
      (JsPath \ "sub_id").read[String] and
      (JsPath \ "min_percentage").read[Byte] and
      (JsPath \ "max_percentage").read[Byte] and
      (JsPath \ "update_time").readNullable[Int] and
      (JsPath \ "status").read[Byte]
    ) (FilterData.apply _)

  implicit val filterDataWrites: Writes[FilterData] = (
    (JsPath \ "id").writeNullable[Int] and
      (JsPath \ "publisher_id").write[Int] and
      (JsPath \ "sub_id").write[String] and
      (JsPath \ "min_percentage").write[Byte] and
      (JsPath \ "max_percentage").write[Byte] and
      (JsPath \ "update_time").writeNullable[Int] and
      (JsPath \ "status").write[Byte]
    ) (unlift(FilterData.unapply))

/**
*         
*/
  def jsonToRead(): Unit = {

    val adResponse = FilterData(
      id = Some(1001),
      publisherId = 10001,
      subId = "213123123",
      minPercentage = 10.toByte,
      maxPercentage = 100.toByte,
      updateTime = Some(1213321),
      status = 0.toByte
    )
    var a = 0
    val stratTime = System.currentTimeMillis()
    while (a < 1) {
      val json = Json.toJson(adResponse)(filterDataWrites)
      json.validate[FilterData](filterDataReads)
      a += 1
    }
    println(System.currentTimeMillis() - stratTime + ": ms")
  }
/**
*            
*/
  def jsonToRead11(): Unit = {
    val adResponse = FilterData(
      id = Some(1001),
      publisherId = 10001,
      subId = "213123123",
      minPercentage = 10.toByte,
      maxPercentage = 100.toByte,
      updateTime = Some(1213321),
      status = 0.toByte
    )
    var a = 0
    import org.json4s.native.Serialization.write
    implicit val formats = org.json4s.DefaultFormats
    val stratTime = System.currentTimeMillis()
    while (a < 1) {
      read[FilterData](write(adResponse))
      a += 1
    }
    println(System.currentTimeMillis() - stratTime + ": ms")
  }

  def main(args: Array[String]): Unit = {
    jsonToRead()
    jsonToRead11()
  }
}


自分でテストしてみてください