If statements within Play/Scala JSON parsing? -


is there way perform conditional logic while parsing json using scala/play?

for example, following:

implicit val playlistiteminfo: reads[playlistiteminfo] = (     (if(( (jspath \ "type1").readnullable[string]) != null){ (jspath \ "type1" \ "id").read[string]} else {(jspath \ "type2" \ "id").read[string]}) ,       (jspath \ "name").readnullable[string]     )(playlistiteminfo.apply _) 

in hypothetical json parsing example, there 2 possible ways parse json. if item of "type1", there value "type1" in json. if not present in json or value null/empty, read json node "type2" instead.

the above example not work, gives idea of trying do.

is possible?

the proper way json combinators use orelse. each piece of combinator must reads[yourtype], if/else doesn't quite work because if clause doesn't return boolean, returns reads[playlistiteminfo] checked against null true. orelse let's combine 1 reads looks type1 field, , second 1 looks type2 field fallback.

this might not follow exact structure, here's idea:

case class playlistiteminfo(id: option[string], tpe: string)  object playlistiteminfo {     implicit val reads: reads[playlistiteminfo] = (         (__ \ "id").readnullable[string] ,         (__ \ "type1").read[string].orelse((__ \ "type2").read[string])     )(playlistiteminfo.apply _) }  // read type 1 on type 2 val js = json.parse("""{"id": "test", "type1": "111", "type2": "2222"}""")  scala> js.validate[playlistiteminfo] res1: play.api.libs.json.jsresult[playlistiteminfo] = jssuccess(playlistiteminfo(some(test),111),)  // read type 2 when type 1 unavailable val js = json.parse("""{"id": "test", "type2": "22222"}""")  scala> js.validate[playlistiteminfo] res2: play.api.libs.json.jsresult[playlistiteminfo] = jssuccess(playlistiteminfo(some(test),22222),)  // error neither val js = json.parse("""{"id": "test", "type100": "fake"}""")  scala> js.validate[playlistiteminfo] res3: play.api.libs.json.jsresult[playlistiteminfo] = jserror(list((/type2,list(validationerror(error.path.missing,wrappedarray()))))) 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -