Spark如何将DataFrame、DataSet、Row转换为Json字符串?
最近遇到一个业务需求,需要将DataFrame中的每一行数据转换为Json字符串并存入mysql库。
话不多说,直接上代码:
package core.test
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import scala.util.parsing.json.JSONObject
object DFTest {
def main(args: Array[String]): Unit = {
val spark: SparkSession = SparkSession.builder()
.appName(s"${this.getClass.getName}_localTest_")
.master("local[*]")
.enableHiveSupport()
.getOrCreate
val testDataFrame: DataFrame =
spark.createDataFrame(Seq(
("1", "asf", null),
("2", "2143", null),
("3", "rfds", null)
)).toDF("label", "col", "contact_way")
def convertRowToJSON(row: Row): String = {
var m: Map[String, String] = row.getValuesMap(row.schema.fieldNames)
m = m.map(v => {
if (v._2 == null) (v._1, "null") else v
})
JSONObject(m).toString()
}
testDataFrame.foreach(row => println(convertRowToJSON(row)))
testDataFrame.show()
}
}
输出结果
{"label" : "3", "col" : "rfds", "contact_way" : "null"}
{"label" : "2", "col" : "2143", "contact_way" : "null"}
{"label" : "1", "col" : "asf", "contact_way" : "null"}
+-----+----+-----------+
|label| col|contact_way|
+-----+----+-----------+
| 1| asf| null|
| 2|2143| null|
| 3|rfds| null|
+-----+----+-----------+
解释说明
- 转换是通过convertRowToJSON这个方法来实现的;
- 要处理map中的value为null的情况,否则会报空指针NullPointer的错误;
- DataFrame可以foreach为row,也可以转换为DataSet,所以此方法针对三种对象都可以使用
踩坑路径
网上搜索类似问题的不少:spark dataFrame转换为Json字符串
- 大部分人需求是将DataFrame转换为Json字符串并写入文件,方法是设置option的时间格式
- 有人提出将org.apache.commons的版本替换为3.5
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
我使用了以上两种方法均未成功。