scala之json4s

GitHub: https://github.com/json4s/json4s

  // 默认隐式转换
  implicit val formats: Formats = DefaultFormats
  
  // 对象转json
  val json = Serialization.write(F(112, "幺幺儿", None, Some("--"), BigDecimal(100d), Some(BigDecimal(23d))))
  // {"id":112,"name":"幺幺儿","content":"--","money":100.0,"pay":23.0}
  
  // json转对象
  val r = Serialization.read[F]("{\"id\":112,\"name\":\"幺幺儿\",\"money\":55}")

针对特殊Bean

例如TEnum作为基础枚举类, 其他枚举继承TEnum:

class Sex private(val id: Int, val name: String) extends com.github.dapeng.core.enums.TEnum(id, name) {}

object Sex {
  val MAN = new Sex(1, "男")
  val WOMAN = new Sex(2, "女")
  val UNDEFINED = new Sex(-1, "UNDEFINED")
}    

如果不自定义序列化和反序列化, 会导致 对象转json 时出现重复的id和name, 所以就需要对这些特殊bean自定义序列化:

val TEnumSerializer = new CustomSerializer[TEnum](_ => (
    { case JObject(JField("id", JInt(id)) :: JField("name", JString(name)) :: Nil) => new TEnum(id.toInt, name) },
    { case e: TEnum => JObject(JField("id", JInt(BigInt(e.getId))) :: JField("name", JString(e.getName)) :: Nil) }
  ))

  implicit val formats: Formats = DefaultFormats + TEnumSerializer

你可能感兴趣的:(scala)