Skip to content

Instantly share code, notes, and snippets.

@mandubian
Forked from zxamplez/CODE
Last active December 14, 2015 09:29
Show Gist options
  • Save mandubian/5065728 to your computer and use it in GitHub Desktop.
Save mandubian/5065728 to your computer and use it in GitHub Desktop.
#Play2.1 #Json Read 2 fields exclusively (accepts only one present) essaimodif #scala #nullable
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
import play.api.libs.json._
import play.api.libs.functional.syntax._
val r = (
(__ \ "field1").readNullable[String] and
(__ \ "field2").readNullable[Int]
).tupled.filter(ValidationError("unexpected result")){
case( Some(x), None ) => true;
case ( None, Some(x) ) => true;
case _ => false
}
scala> Json.obj("field1" -> "toto").validate(r)
res19: play.api.libs.json.JsResult[(Option[String], Option[Int])] = JsSuccess((Some(toto),None),)
scala> Json.obj("field2" -> 5).validate(r)
res20: play.api.libs.json.JsResult[(Option[String], Option[Int])] = JsSuccess((None,Some(5)),)
scala> Json.obj("field2" -> "toto").validate(r)
res21: play.api.libs.json.JsResult[(Option[String], Option[Int])] = JsError(List((/field2,List(ValidationError(validate.error.expected.jsnumber,WrappedArray())))))
scala> Json.obj("field1" -> "toto", "field2" -> 5).validate(r)
res22: play.api.libs.json.JsResult[(Option[String], Option[Int])] = JsError(List((,List(ValidationError(unexpected result,WrappedArray())))))
@Dnomyar
Copy link

Dnomyar commented May 7, 2015

Thanks !

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