Created
May 2, 2014 23:41
-
-
Save benkolera/11488835 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 argonaut._ , Argonaut._ | |
object Recursive { | |
val jsonStr0 = """{ | |
| "name": "name1", | |
| "entities": [] | |
|} | |
""".stripMargin | |
val jsonStr1 = """{ | |
| "name": "name1", | |
| "entities": [ | |
| { | |
| "value": "enitity1", | |
| "dependents": [] | |
| } | |
| ] | |
|} | |
|""".stripMargin | |
val jsonStr2 = """{ | |
| "name": "name1", | |
| "entities": [ | |
| { | |
| "value": "enitity1", | |
| "dependents": [ | |
| { | |
| "name": "name2", | |
| "entities": [ | |
| { "value":"entity2", "dependents":[] } | |
| ] | |
| } | |
| ] | |
| } | |
| ] | |
|} | |
""".stripMargin | |
case class Entity( value:String , dependents:List[Dependent] ) | |
case class Dependent( name:String , entities: List[Entity] ) | |
// Both of these NPE... :( | |
// implicit val entityCodec0:CodecJson[Entity] = | |
// casecodec2( Entity.apply , Entity.unapply )( | |
// "value" , | |
// "dependents" | |
// ) | |
// implicit val entityCodec1:CodecJson[Entity] = | |
// casecodec2( Entity.apply , Entity.unapply )( | |
// "value" , | |
// "dependents" | |
// )( | |
// StringEncodeJson, | |
// StringDecodeJson, | |
// ListEncodeJson[Dependent](dependentCodec), | |
// ListDecodeJson[Dependent](dependentCodec) | |
// ) | |
implicit val entityCodec:CodecJson[Entity] = CodecJson[Entity]( | |
e => Json.obj( | |
"value" -> e.value.asJson , | |
"dependents" -> ListEncodeJson[Dependent](dependentCodec).encode( e.dependents )), | |
c => for { | |
n <- (c --\ "value").as[String] | |
ds <- (c --\ "dependents").as[List[Dependent]](ListDecodeJson(dependentCodec)) | |
} yield Entity( n , ds ) | |
) | |
implicit val dependentCodec:CodecJson[Dependent] = | |
casecodec2( Dependent.apply , Dependent.unapply )( | |
"name" , | |
"entities" | |
) | |
def main( args: Array[String] ): Unit = { | |
List(jsonStr0,jsonStr1,jsonStr2).map( _.decode[Dependent] ).foreach( | |
println _ | |
) | |
} | |
/* Results: | |
* [info] Compiling 1 Scala source to /Users/ben/src/examples/scala/argonaut/target/scala-2.10/classes... | |
* [info] Running Recursive | |
* \/-(Dependent(name1,List())) | |
* \/-(Dependent(name1,List(Entity(enitity1,List())))) | |
* \/-(Dependent(name1,List(Entity(enitity1,List(Dependent(name2,List(Entity(entity2,List())))))))) | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment