您可以使用getValuesMap
将行对象转换为Map,然后将其转换为JSON:
import scala.util.parsing.json.JSONObject import org.apache.spark.sql._ val df = Seq((1,2,3),(2,3,4)).toDF("A", "B", "C") val row = df.first() // this is an example row object def convertRowToJSON(row: Row): String = { val m = row.getValuesMap(row.schema.fieldNames) JSONObject(m).toString() } convertRowToJSON(row) // res46: String = {"A" : 1, "B" : 2, "C" : 3}