github:
使用 json4s库
依赖:
val json4sNative = "org.json4s" %% "json4s-native" % "3.2.11"
数据类型:
sealed abstract class JValuecase object JNothing extends JValue // 'zero' for JValuecase object JNull extends JValuecase class JString(s: String) extends JValuecase class JDouble(num: Double) extends JValuecase class JDecimal(num: BigDecimal) extends JValuecase class JInt(num: BigInt) extends JValuecase class JLong(num: Long) extends JValuecase class JBool(value: Boolean) extends JValuecase class JObject(obj: List[JField]) extends JValuecase class JArray(arr: List[JValue]) extends JValuetype 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 ] } */ }}