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

时间:2014-12-13 07:21:24

标签: scala json4s lift-json

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

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
}

1 个答案:

答案 0 :(得分:3)

您可以将Json4用于此目的(在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)
}