Scala的Json序列化
import java.util.TimeZone import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper} import com.fasterxml.jackson.datatype.joda.JodaModule import com.fasterxml.jackson.module.scala.DefaultScalaModule import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper object JsonUtil { val mapper = new ObjectMapper() with ScalaObjectMapper mapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")) mapper.registerModule(DefaultScalaModule) mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) mapper.registerModule(new JodaModule) def toJson(value: Map[Symbol, Any]): String = { toJson(value map { case (k, v) => k.name -> v }) } def toJson(value: Any): String = { mapper.writeValueAsString(value) } def toMap[V](json: String)(implicit m: Manifest[V]) = fromJson[Map[String, V]](json) def fromJson[T](json: String)(implicit m: Manifest[T]): T = { mapper.readValue[T](json) } }
build.sbt 中需要引用依赖
libraryDependencies += "com.fasterxml.jackson.module" % "jackson-module-scala_2.11" % "2.8.4"
libraryDependencies += "com.fasterxml.jackson.core" % "jackson-databind" % "2.5.4"
libraryDependencies += "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.8.4"
//转json val json = JsonUtil.toJson(obj) //解json,这里T是具体类型 val obj = JsonUtil.fromJson[T](json)
浙公网安备 33010602011771号