json数据格式:
[{"studentName":"lily","studentAge":12},{"studentName":"lucy","studentAge":15}]
pom:
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.44</version>
</dependency>
val conf = new SparkConf().setMaster("local").setAppName("json test")
val sc = new SparkContext(conf)
val textFile = sc.textFile("f:/data/*.txt")
textFile.map(JSON.parseArray) //解析为json数组
.flatMap(_.toArray) //json数组转为java数组,通过flatmap拉平
.map(_.asInstanceOf[JSONObject]) //把每个对象转成jsonobject
.map(x => (x.getString("studentName"), (x.getInteger("studentAge"), 1))) //通过jsonobject的方法处理数据