diff --git a/build.sbt b/build.sbt index 7c8827c..6b1966e 100644 --- a/build.sbt +++ b/build.sbt @@ -12,3 +12,5 @@ libraryDependencies ++= Seq( ) testOptions in Test += Tests.Argument(TestFrameworks.JUnit, "-a", "-v", "-s") + +initialCommands in console := """import codecs.{_, given}""" diff --git a/src/main/scala/codecs/codecs.scala b/src/main/scala/codecs/codecs.scala index a4073b8..f4406dd 100644 --- a/src/main/scala/codecs/codecs.scala +++ b/src/main/scala/codecs/codecs.scala @@ -256,10 +256,10 @@ object Main { val maybeJsonObj = parseJson(""" { "name": "Alice", "age": 42 } """) val maybeJsonObj2 = parseJson(""" { "name": "Alice", "age": "42" } """) // Uncomment the following lines as you progress in the assignment - // println(maybeJsonString.toOption.flatMap(_.decodeAs[Int])) - // println(maybeJsonString.toOption.flatMap(_.decodeAs[String])) - // println(maybeJsonObj.toOption.flatMap(_.decodeAs[Person])) - // println(maybeJsonObj2.toOption.flatMap(_.decodeAs[Person])) + // println(maybeJsonString.flatMap(_.decodeAs[Int])) + // println(maybeJsonString.flatMap(_.decodeAs[String])) + // println(maybeJsonObj.flatMap(_.decodeAs[Person])) + // println(maybeJsonObj2.flatMap(_.decodeAs[Person])) // println(renderJson(Person("Bob", 66))) } diff --git a/src/main/scala/codecs/json.scala b/src/main/scala/codecs/json.scala index ccd00a2..7317824 100644 --- a/src/main/scala/codecs/json.scala +++ b/src/main/scala/codecs/json.scala @@ -8,20 +8,21 @@ import scala.util.Try // render values to `String` JSON blobs /** - * Parse a JSON document contained in a `String` value into a `Json` value + * Parse a JSON document contained in a `String` value into a `Json` value, returns + * `None` in case the supplied `s` value is not a valid JSON document. */ -def parseJson(s: String): Try[Json] = Parser.parseFromString[Json](s) +def parseJson(s: String): Option[Json] = Parser.parseFromString[Json](s).toOption /** * Parse the JSON value from the supplied `s` parameter, and then try to decode * it as a value of type `A` using the given `decoder`. * - * Returns a failure if JSON parsing failed, or if decoding failed. + * Returns `None` if JSON parsing failed, or if decoding failed. */ -def parseAndDecode[A](s: String)(given decoder: Decoder[A]): Try[A] = +def parseAndDecode[A](s: String)(given decoder: Decoder[A]): Option[A] = for { - json <- parseJson(s) - a <- decoder.decode(json).toRight(new Exception("Decoding failed")).toTry + json <- parseJson(s) + a <- decoder.decode(json) } yield a /**