3

Is it possible to serialize object of below class using Json4s or lift or any other library?

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
}
senia
  • 37,745
  • 4
  • 88
  • 129
alchemist
  • 41
  • 4

1 Answers1

4

You can use Json4s for this purpose (with help of FieldSerializer), below is the code to get started with serialization of the User object:

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))
}

Also, in your non case class anything which is missing from the JSON needs to be an Option.

Another method would be to go for 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)
}
nitishagar
  • 9,038
  • 3
  • 28
  • 40
  • the first option didn't work. The compiler was not recognizing the main class if I use the first option – alchemist Dec 13 '14 at 20:41
  • the first option didn't work for me. The compiler was not recognizing the main class if I use the first option. the second option worked fine but only after declaring User class as case class. Thanks a lot for your help. Would you know why the first option didn't work? – alchemist Dec 13 '14 at 20:48
  • genson is not serializing a Char to json...any ideas why? – alchemist Dec 13 '14 at 22:47
  • Can you provide in more detail on the error you get when you try the first option. Also, both of the option worked for me without case class specification. – nitishagar Dec 14 '14 at 03:21
  • @alchemist could you please post an example of the code you are using to ser/de the char? Btw it should also work with a class (just the ser/de rules are slightly different than for case classes) – eugen Dec 17 '14 at 00:41