scala - 是否可以在 Scala 中序列化非案例类?

标签 scala json4s lift-json

是否可以使用 Json4s 或 lift 或任何其他库序列化以下类的对象?

class User(uId: Int) extends Serializable {
  var id: Int = uId
  var active: Boolean = false
  var numTweets: Int = 0
  var followers: ArrayBuffer[Int] = null
  var following: ArrayBuffer[Int] = null
  var userTimeline: Queue[String] = null
  var homeTimeline: Queue[String] = null
  var userTimelineSize: Int = 0
  var homeTimelineSize: Int = 0
  //var notifications: Queue[String] = null
  var mentions: Queue[String] = null
  var directMessages: Queue[String] = null
}

最佳答案

您可以为此目的使用 Json4s(在 FieldSerializer 的帮助下),下面是开始序列化 User 对象的代码:

def main(args: Array[String]) {
    import org.json4s._
    import org.json4s.native.Serialization
    import org.json4s.native.Serialization.{read, write, writePretty}

    implicit val formats = DefaultFormats + FieldSerializer[User]()

    val user = new User(12)

    val json = write(user)
    println(writePretty(user))
}

此外,在您的非案例类中,JSON 中缺少的任何内容都需要是一个选项。

另一种方法是寻找 Genson :

def main(args: Array[String]) {
    import com.owlike.genson._
    import com.owlike.genson.ext.json4s._
    import org.json4s._
    import org.json4s.JsonDSL._
    import org.json4s.JsonAST._

    object CustomGenson {
      val genson = new ScalaGenson(
        new GensonBuilder()
        .withBundle(ScalaBundle(), Json4SBundle())
        .create()
      )
    }

    // then just import it in the places you want to use this instance instead of the default one
    import CustomGenson.genson._

    val user = new User(12)    

    val jsonArray = toJson(user)
    println(jsonArray)
}

关于scala - 是否可以在 Scala 中序列化非案例类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27456548/

相关文章:

json - 存储案例对象时使用哪个 JSON 库?

scala - 如何将 JNothing 序列化为 null

java - 使用 lift-json 根据 json 和元数据实例化一个类型

json - 用 1 个元素解析 Json 列表(Scala/liftweb)

scala - 如何更改 Akka 和 Logback 日志记录级别

scala - 在数据帧上执行 groupby 时连接 maptype 值

scala - 要么单元操作

json - 未找到隐式参数

json - scala - 使用 json4s 分解时如何更改字段名称?