Created
April 8, 2022 23:34
-
-
Save daharon/3872439fdf4ef40d3d5e613da91427e6 to your computer and use it in GitHub Desktop.
Extension method to deserialize JSON string to object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package us.aharon.test.json | |
import com.fasterxml.jackson.databind.json.JsonMapper | |
import com.fasterxml.jackson.module.scala.DefaultScalaModule | |
import scala.reflect.{ClassTag, classTag} | |
/** | |
* Extension methods for [[String]]s. | |
*/ | |
private object StringExtension { | |
/** | |
* [[String]]s that contain JSON objects. | |
*/ | |
implicit class JsonString(self: String) { | |
/** | |
* Convert the JSON [[String]] to the type provided by [[T]]. | |
* @param mapper A Jackson JSON mapper instance. | |
* @tparam T Deserialize to this type. | |
*/ | |
def fromJson[T: ClassTag]()(implicit mapper: JsonMapper): T = | |
mapper.readValue(self, classTag[T].runtimeClass.asInstanceOf[Class[T]]) | |
} | |
} | |
/** | |
* Include the implicit JSON mapper. | |
*/ | |
trait JsonSupport { | |
implicit val mapper: JsonMapper = JsonMapper.builder() | |
.addModule(DefaultScalaModule) | |
.build() | |
} | |
object JacksonJsonSugar extends App with JsonSupport { | |
/** | |
* Example object as a target for JSON deserialization. | |
*/ | |
case class Example(a: Int, b: Double, c: String) | |
val exampleJson = | |
""" | |
|{ | |
| "a": 1, | |
| "b": 2.2, | |
| "c": "example" | |
|}""".stripMargin | |
val expected = Example(1, 2.2, "example") | |
import us.aharon.test.json.StringExtension.JsonString | |
val actual = exampleJson.fromJson[Example] | |
println(s"Example JSON:\n$exampleJson") | |
println(s"Expected: $expected") | |
println(s"Actual: $actual") | |
assert(expected == actual) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment