scala 对象转Json和Json转对象的俩种方式

  • Post author:
  • Post category:其他


直接进入正题

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

大家可以自己测试一下



版权声明:本文为u013412790原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。