Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Custom serializer should work with Option

  • Loading branch information...
commit b925803ff5592e12b4f39b2c9e8c137f8f2bd395 1 parent e8aed79
Joni Freeman authored
22 core/json/src/main/scala/net/liftweb/json/Extraction.scala
View
@@ -270,15 +270,19 @@ object Extraction {
case x => fail("Expected array but got " + x)
}
- def mkValue(root: JValue, mapping: Mapping, path: String, optional: Boolean) = try {
- val x = build(root, mapping)
- if (optional) {
- if (x == null) None else Some(x)
- } else x
- } catch {
- case MappingException(msg, _) =>
- if (optional) None else fail("No usable value for " + path + "\n" + msg)
- }
+ def mkValue(root: JValue, mapping: Mapping, path: String, optional: Boolean) =
+ if (optional && root == JNothing) None
+ else {
+ try {
+ val x = build(root, mapping)
+ if (optional) {
+ if (x == null) None else Some(x)
+ } else x
+ } catch {
+ case MappingException(msg, _) =>
+ if (optional) None else fail("No usable value for " + path + "\n" + msg)
+ }
+ }
def fieldValue(json: JValue): JValue = json match {
case JField(_, value) => value
24 core/json/src/test/scala/net/liftweb/json/SerializationBugs.scala
View
@@ -18,7 +18,7 @@ package net.liftweb
package json
import org.specs.Specification
-
+import java.util.UUID
object SerializationBugs extends Specification {
import Serialization.{read, write => swrite}
@@ -67,6 +67,26 @@ object SerializationBugs extends Specification {
val ser = swrite(xs)
read[LongList](ser).xs.length mustEqual 5000
}
+
+ "Custom serializer should work with Option" in {
+ class UUIDFormat extends Serializer[UUID] {
+ val UUIDClass = classOf[UUID]
+
+ def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), UUID] = {
+ case (TypeInfo(UUIDClass, _), JString(x)) => UUID.fromString(x)
+ }
+
+ def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
+ case x: UUID => JString(x.toString)
+ }
+ }
+
+ implicit val formats = Serialization.formats(NoTypeHints) + new UUIDFormat
+ val o1 = OptionalUUID(None)
+ val o2 = OptionalUUID(Some(UUID.randomUUID))
+ read[OptionalUUID](swrite(o1)) mustEqual o1
+ read[OptionalUUID](swrite(o2)) mustEqual o2
+ }
}
case class LongList(xs: List[Num])
@@ -75,6 +95,8 @@ case class Num(x: Int)
case class X(yy: Y)
case class Y(ss: String)
+case class OptionalUUID(uuid: Option[UUID])
+
package plan1 {
case class Plan(plan: Option[Action])
case class Game(game: Map[String, Plan])
Please sign in to comment.
Something went wrong with that request. Please try again.