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

直接进入正题

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").writeNullab
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Scala 中,你可以使用 `play-json` 库来进行 JSON 数据与对象之间的换。下面是一个简单的例子: 首先,你需要在 `build.sbt` 文件中添加 `play-json` 依赖: ```scala libraryDependencies += "com.typesafe.play" %% "play-json" % "2.9.2" ``` 然后,你需要定义一个 case class 来表示 JSON 数据的结构。例如,假设你有以下的 JSON 数据: ```json { "name": "John Doe", "age": 30, "email": "john.doe@example.com" } ``` 你可以定义一个对应的 case class: ```scala import play.api.libs.json._ case class Person(name: String, age: Int, email: String) object Person { implicit val format: Format[Person] = Json.format[Person] } ``` 在这个例子中,我们使用 `Json.format` 定义了一个 `Person` 的 `Format`,它将自动推导出如何将 JSON 数据换为 `Person` 对象以及将 `Person` 对象换为 JSON 数据。 现在,你可以使用 `Json.parse` 将 JSON 数据解析为 `JsValue`,然后将其换为 `Person` 对象: ```scala import play.api.libs.json._ val json = Json.parse(""" { "name": "John Doe", "age": 30, "email": "john.doe@example.com" } """) val person = json.as[Person] println(person.name) // 输出 "John Doe" ``` 在这个例子中,我们使用 `Json.parse` 将 JSON 字符串解析为 `JsValue`,然后使用 `as` 方法将其换为 `Person` 对象。 如果 JSON 数据中有一些字段在 `Person` 中没有对应的属性,或者 `Person` 中有一些属性没有在 JSON 数据中出现,`play-json` 会自动忽略它们。如果 JSON 数据中的某些字段类型与 `Person` 中的属性类型不匹配,`as` 方法会抛出一个异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值