github: https://github.com/json4s/json4sjava
使用 json4s庫
依賴:
val json4sNative = "org.json4s" %% "json4s-native" % "3.2.11"
數據類型:
sealed abstract class JValue case object JNothing extends JValue // 'zero' for JValue case object JNull extends JValue case class JString(s: String) extends JValue case class JDouble(num: Double) extends JValue case class JDecimal(num: BigDecimal) extends JValue case class JInt(num: BigInt) extends JValue case class JLong(num: Long) extends JValue case class JBool(value: Boolean) extends JValue case class JObject(obj: List[JField]) extends JValue case class JArray(arr: List[JValue]) extends JValue type JField = (String, JValue)
demo:
import org.json4s.JsonDSL._ import org.json4s.jackson.JsonMethods._ import org.json4s._ object Json4sTest { def main(args: Array[String]): Unit = { implicit val format = DefaultFormats val str = """{"table":"spark_test.user","op_type":"I","op_ts":"2018-05-21 15:29:35.655148","after":{"ID":111, "name":"張三"}}""" val jValue: JValue = parse(str) println(jValue) // JObject(List((table,JString(spark_test.user)), (op_type,JString(I)), (op_ts,JString(2018-05-21 15:29:35.655148)), (after,JObject(List((ID,JInt(111)), (name,JString(張三))))))) val res2 = (jValue \ "after") println(res2) //JObject(List((ID,JInt(111)), (name,JString(張三)))) val res3 = res2.values println(res3) //Map(ID -> 111, name -> 張三) val r = ("name" -> "abc") ~ ("class" -> 123) ~ ("timestamp" -> System.currentTimeMillis()) ~ ("age" -> Seq(1, 2, 3)) println(compact(render(r))) //{"name":"abc","class":123,"timestamp":1527573731901,"age":[1,2,3]} println(pretty(render(r))) /* { "name" : "abc", "class" : 123, "timestamp" : 1527573731901, "age" : [ 1, 2, 3 ] } */ } }