Last active
August 29, 2015 14:06
-
-
Save tldeti/56058628eebfab850d36 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scalaz._ | |
import Scalaz._ | |
import argonaut._ | |
import Argonaut._ | |
/** | |
* Created by tldeti on 14-9-23. | |
*/ | |
object Tags { | |
sealed trait WithDefault | |
def TWIthDefault[A](a: A): A @@ WithDefault = Tag[A, WithDefault](a) | |
} | |
import Tags._ | |
object Decodes { | |
implicit val stringDefaultDecode: DecodeJson[String @@ WithDefault] = DecodeJson( | |
h => | |
h.as[String].map(x => | |
Tags.TWIthDefault( | |
if (x.trim.isEmpty) | |
"not Supplied" | |
else | |
x | |
) | |
) | |
) | |
} | |
import Decodes._ | |
object test extends App { | |
case class Eg(a:String,b:String) | |
val tt = Eg("","x") | |
val ttt = Eg("x","") | |
implicit val decodeA:DecodeJson[Eg] = DecodeJson( | |
h=> | |
for{ | |
a <- (h --\ "a").as[String @@ WithDefault] | |
b <- (h --\ "b").as[String] | |
} yield Eg(Tag.unwrap(a),b) | |
) | |
implicit val encodeA:EncodeJson[Eg] = | |
jencode2L((p: Eg) => (p.a, p.b))("a", "b") | |
tt.asJson.as[Eg].fold((x,y)=> throw new RuntimeException("eror"),m=> | |
assert(Eg("not Supplied","x") == m) | |
) | |
ttt.asJson.as[Eg].fold((x,y)=> throw new RuntimeException("eror"),m=> | |
assert(Eg("x","") == m) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment