Skip to content

Commit

Permalink
Merge pull request #318 from commercetools/JSON_instance
Browse files Browse the repository at this point in the history
find JSON instance from FromJSON and ToJSON
  • Loading branch information
yanns authored Jun 17, 2021
2 parents e3874b7 + fec9aef commit c7fe416
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
12 changes: 11 additions & 1 deletion json/json-core/src/main/scala/io/sphere/json/JSON.scala
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
package io.sphere.json

import org.json4s.JsonAST.JValue

import scala.annotation.implicitNotFound

@implicitNotFound("Could not find an instance of JSON for ${A}")
trait JSON[A] extends FromJSON[A] with ToJSON[A]

object JSON {
object JSON extends JSONLowPriorityImplicits {
@inline def apply[A](implicit instance: JSON[A]): JSON[A] = instance
}

trait JSONLowPriorityImplicits {
implicit def fromJSONAndToJSON[A](implicit fromJSON: FromJSON[A], toJSON: ToJSON[A]): JSON[A] =
new JSON[A] {
override def read(jval: JValue): JValidation[A] = fromJSON.read(jval)
override def write(value: A): JValue = toJSON.write(value)
}
}

class JSONException(msg: String) extends RuntimeException(msg)

sealed abstract class JSONError
Expand Down
27 changes: 27 additions & 0 deletions json/json-core/src/test/scala/io/sphere/json/JSONSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package io.sphere.json

import org.json4s.JsonAST.JValue
import org.scalatest.matchers.must.Matchers
import org.scalatest.wordspec.AnyWordSpec

class JSONSpec extends AnyWordSpec with Matchers {
import JSONSpec._
"JSON.apply" must {
"find possible JSON instance" in {
implicit val testJson: JSON[Test] = new JSON[Test] {
override def read(jval: JValue): JValidation[Test] = ???
override def write(value: Test): JValue = ???
}
JSON[Test] must be(testJson)
}
"create instance from FromJSON and ToJSON" in {
JSON[Int]
JSON[List[Double]]
JSON[Map[String, Int]]
}
}
}

object JSONSpec {
case class Test(a: String)
}

0 comments on commit c7fe416

Please sign in to comment.