Skip to content

Serialization and Deserialization

Michal Kovac edited this page Feb 25, 2015 · 2 revisions

Form serialize and deserialize

import com.github.aselab.activerecord._
import com.github.aselab.activerecord.dsl._

case class Person(name: String, age: Int) extends ActiveModel

object Person extends ActiveModelCompanion[Person]

Person("bob", 20).toFormValues
// => Map("name" -> "bob", "age" -> "20")

Person.bind(Map("name" -> "john", "age" -> "25"))
// => Person("john", 25)

JSON serialize and deserialize

Note : Available version 0.3.1 or later.

import com.github.aselab.activerecord._
import com.github.aselab.activerecord.dsl._

case class Person(name: String, age: Int) extends ActiveModel

object Person extends ActiveModelCompanion[Person]

Person("bob", 20).toJson
// => {"name":"bob","age": 20}

Person("bob", 20).toJson("age")
// => {"age":20}

Person("bob", 20).toJson("name", "age")
// => {"name":"bob","age": 20}

Person.fromJson("""{"name":"john", "age": 25}""")
// => Person("john", 25)

Iterable objects

List(Person("bob", 20), Person("john", 25)).toJson
// => [{"name":"bob", "age": 20}, {"name":"john", "age": 25}]

Person.fromArrayJson("""[{"name":"bob", "age": 20},{"name":"john", "age": 25}]""")
// => List(Person("bob", 20), Person("john", 25))

GroupBy objects

List(Person("bob", 20), Person("john", 25), Person("smith", 20)).groupBy(_.age).toJson
// => {"20":[{"name":"bob", "age": 20},{"name":"smith", "age": 20}],"25":[{"name":"john", "age": 25}]}

Convert to json4s JValue object

Person("bob", 20).asJson
// => JObject((name,JString(bob), (age,JInt(20)))

Person.fromJValue(Person("john", 25).asJson)
// => Person("john", 25)

List(Person("bob", 20), Person("john", 25)).asJson
// => JArray(List(JObject((name,JString(bob), (age,JInt(20))), JObject((name,JString(john), (age,JInt(25)))))

Person.fromJArray(List(Person("bob", 20), Person("john", 25)).asJson)
// => List(Person("bob", 20), Person("john", 25))