Skip to content

Instantly share code, notes, and snippets.

@arschles
Created November 18, 2012 06:25
Show Gist options
  • Save arschles/4103868 to your computer and use it in GitHub Desktop.
Save arschles/4103868 to your computer and use it in GitHub Desktop.
making lift-json easier
import scalaz._
import Scalaz._
import net.liftweb.json._
import net.liftweb.json.scalaz.JsonScalaz._
def json[T](serialize: T => JValue, deserialize: JValue => Result[T]): JSON[T] = new JSON[T] {
def write(t: T) = serialize(t)
def read(jval: JValue): Result[T] = deserialize(jval)
}
//usage
case class MyClass(i: Int)
implicit val myClassSerializer = json[MyClass](
serialize = C => i: JValue,
deserialize = j => ????
)
@drapp
Copy link

drapp commented Nov 26, 2012

This is nicer, but I'd still have to do

case class MyClass(i: Int)

val iJsonKey = "i"

implicit val myClassSerializer = json[MyClass](
  serialize = (myClass: MyClass) => (iJsonKey -> myClass.i): JValue
  deserialize = (j: JValue) => field[Int](iJsonKey)(j).map(MyClass(_))
)

There's still the possibility to get this wrong with a stupid mistake, like copying a line and ending up with the wrong string tied to the wrong field. Perhaps something like this that gets the field types from reflection? Presumably that's what other case class serializers do

@arschles
Copy link
Author

nothing that sophisticated. I wrote this to help avoid writing the boilerplate of writing new JSON[T] {....}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment