Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. // This is an example of how to express Infinity in Json using the Play! Scala Json library.
  2. // Infinity cannot be expressed as a Scalar value in Json, so I am using an object to hold it instead.
  3. //
  4. // Example of a finite value:
  5. // {
  6. // "value": 12.009,
  7. // "isInfinite": false
  8. // }
  9. //
  10. // Example of an infinite value:
  11. // {
  12. // "value": null,
  13. // "isInfinite": true
  14. // }
  15. //
  16. // It should be used as any other reads, for example:
  17. // jsonPayload.as[PossiblyInfinite]
  18.  
  19. case class PossiblyInfinite(value: Double) {
  20. val isInfinite: Boolean = value.isInfinite
  21. }
  22.  
  23. object PossiblyInfinite {
  24.  
  25. def Infinite: PossiblyInfinite = PossiblyInfinite(Double.PositiveInfinity)
  26.  
  27. private val VALUE_KEY = "value"
  28. private val IS_INFINITE_KEY = "isInfinite"
  29.  
  30. implicit val writes: Writes[PossiblyInfinite] = new Writes[PossiblyInfinite] {
  31. override def writes(o: PossiblyInfinite): JsValue = {
  32. if (o.isInfinite) {
  33. Json.obj(VALUE_KEY -> JsNull, IS_INFINITE_KEY -> true)
  34. } else {
  35. Json.obj(VALUE_KEY -> o.value, IS_INFINITE_KEY -> false)
  36. }
  37. }
  38. }
  39.  
  40. implicit object PossiblyInfiniteReads extends Reads[PossiblyInfinite] {
  41. override def reads(json: JsValue): JsResult[PossiblyInfinite] = {
  42.  
  43. val maybeDouble = json.asOpt[Double]
  44. lazy val maybeValue = (json \ VALUE_KEY).asOpt[Double]
  45. lazy val maybeIsInfinite = (json \ IS_INFINITE_KEY).asOpt[Boolean]
  46.  
  47. // If this was a scalar double, use its value
  48. if (maybeDouble.isDefined) {
  49. JsSuccess(PossiblyInfinite(maybeDouble.get))
  50. }
  51.  
  52. // If it wasn't a scalar double, check the other properties
  53. else {
  54. (maybeValue, maybeIsInfinite) match {
  55.  
  56. // Case 1: value is defined (it can't be Infinite here because JSON doesn't allow it)
  57. case (Some(value), _) => JsSuccess(PossiblyInfinite(value))
  58.  
  59. // Case 2: isInfinite is true
  60. case (_, Some(true)) => JsSuccess(PossiblyInfinite.Infinite)
  61.  
  62. // Case 3: there isn't enough information
  63. case _ => JsError(s"Either ${JsPath() \ VALUE_KEY} must be provided, or ${JsPath() \ IS_INFINITE_KEY} must be provided as true")
  64. }
  65. }
  66. }
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement