scala - json4s操作

第一步:导入依赖

        <dependency>
            <groupId>org.json4s</groupId>
            <artifactId>json4s-native_2.12</artifactId>
            <version>3.5.4</version>
        </dependency>

第二步:具体操作

import java.sql.Timestamp

import org.json4s._
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization

object JsonUtil {

  case object TimestampSerializer extends CustomSerializer[java.sql.Timestamp](format => ( {
    case _ => null
  }, {
    case ts: Timestamp => JLong(ts.getTime)
  })
  )

  implicit val formats = DefaultFormats + TimestampSerializer

  /**
    * json 转 map
    *
    * @param content
    * @return
    */
  def jsonToMap(content: String): Map[String, Any] = {
    parse(content).extract[Map[String, Any]]
  }

  /**
    * json 转对象
    *
    * @param content
    * @tparam T
    * @return
    */
  def jsonToObj[T: Manifest](content: String): T = {
    parse(content).extract[T]
  }

  def jsonToObj[T: Manifest](content: AnyRef): T = {
    parse(toJson(content)).extract[T]
  }

  /**
    * json 转 list
    *
    * @param content
    * @tparam T
    * @return
    */
  def jsonToList[T: Manifest](content: String): List[T] = {
    parse(content).extract[List[T]]
  }

  /**
    * 对象转json
    *
    * @param obj
    * @return
    */
  def toJson(obj: AnyRef): String = {
    try {
      Serialization.write(obj)
    } catch {
      case ex: Exception => throw new Exception("转json异常", ex.getCause)
    }
  }

  def toJson2(obj: List[Map[String, Any]]): String = {
    Serialization.write(obj)
  }

 

posted @ 2021-01-04 14:49  快乐的张小凡  阅读(479)  评论(0编辑  收藏  举报