scala
[scala] jackson, ujson
'김용환'
2019. 10. 4. 11:58
scala 에서 json을 사용할 때 jackson을 바인딩하는 것다..
import java.util.TimeZone
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.databind.util.StdDateFormat
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
object JasksonJsonUtil {
val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
val stdDateFormat = new StdDateFormat()
stdDateFormat.setTimeZone(TimeZone.getDefault)
mapper.setDateFormat(stdDateFormat)
def toJson(value: Object): String = {
mapper.writeValueAsString(value)
}
}
ujson이 좀 나은 것 같다.
ujson에서는 scala 계에서 유명한 lihaoyi 라이브러리(com.lihaoyi:ujson)를 활용한다.
import org.scalatest.{FunSuite, Matchers}
import java.text.SimpleDateFormat
import java.util.Date
import ujson.Value
class JasksonJsonUtilTest extends FunSuite with Matchers {
test("JacksonJsonUtil.toJson") {
case class Model(name: String, date: Date)
val actual = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .parse("2019-10-04T10:14:27.783+0900")
val json: String = JasksonJsonUtil.toJson(Model("expire", actual))
UJson(json).get("date").str should be("2019-10-04T10:14:27.783+0900")
}
case class UJson(jsonString: String) {
val value: Value = ujson.read(jsonString)
def get(keys: String): Value.Value = {
var x = value
keys.split("[.]").foreach { key =>
x = x(key)
}
x
}
}
}