当前位置: 首页 > 工具软件 > Scala JSON > 使用案例 >

Scala json字符串和对象互转

钦侯林
2023-12-01

官网介绍lift-json

Maven依赖

<dependency>
 	<groupId>net.liftweb</groupId>
    <artifactId>lift-mapper_2.11</artifactId>
    <version>3.4.1</version>
</dependency>

json字符串,对象互转

  1. 定义case class
case class ShockArrayEvent(imei: String, time: Long, gm: List[List[Int]])
  1. 转换
import net.liftweb.json._
import net.liftweb.json.Serialization.write

object MyTest {

  def main(args: Array[String]): Unit = {
    implicit val formats: DefaultFormats.type = DefaultFormats
    val json: String = "{\"gimei\": \"861050045442715\", \"gm\": [[124, 119, 1081], [123, 112, 1087]], \"imei\": \"1000007\", \"time\": 1598647456, \"hc\": \"75.2\", \"tc\": \"27.1\"}";
    //JSON字符串转对象
    val event = parse(json).extract[ShockArrayEvent]
    //对象转JSON字符串
    val value = write[ShockArrayEvent](event)
    println(value)
  }
}
 类似资料: