json数据

  1. [{"name":"张三" ,"age":18} ,{"name":"李四" ,"age":15}]

不能是多行的,一定要一行的.

代码

  1. import org.apache.spark.sql.{DataFrame, SparkSession}
  2. case class People(name: String, age: Long)
  3. object DFDS {
  4. def main(args: Array[String]): Unit = {
  5. val spark: SparkSession = SparkSession
  6. .builder()
  7. .master("local[*]")
  8. .appName("DFDS")
  9. .getOrCreate()
  10. import spark.implicits._
  11. val df: DataFrame = spark.read.json("E:\\ZJJ_SparkSQL\\demo01\\src\\main\\resources\\users.json")
  12. // 先有一个样例类
  13. val ds = df.as[People] // 转成DataSet
  14. ds.show()
  15. println("------")
  16. val df1: DataFrame = ds.toDF() //转成DataFrame
  17. df1.show
  18. spark.close()
  19. }
  20. }

输出

  1. +---+----+
  2. |age|name|
  3. +---+----+
  4. | 18| 张三|
  5. | 15| 李四|
  6. +---+----+
  7. ------
  8. +---+----+
  9. |age|name|
  10. +---+----+
  11. | 18| 张三|
  12. | 15| 李四|
  13. +---+----+