You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从JSON文件创建StructType作为DataFrame Schema时遭遇DataType.fromJson()类型转换错误的求助

解决Spark中从JSON创建StructType时的类型转换错误

我看到你在尝试通过JSON文件定义Spark的StructType作为DataFrame Schema时遇到了类型转换错误,这个问题其实是因为Spark对DataType的JSON格式有特定要求,咱们一步步来解决:

问题根源

你遇到的java.lang.IllegalArgumentException: Failed to convert the JSON string 'int' to a data type错误,核心原因是Spark的DataType JSON解析器不识别"int"这个简写类型名。Spark要求基础类型必须使用它标准的类型名称,比如整数类型对应的是"integer"而不是"int"。

修改后的正确JSON Schema

把你原来的JSON里的"type": "int"改成"type": "integer"即可,修改后的完整JSON如下:

{
  "type": "struct",
  "fields": [
    {
      "name": "LocationID",
      "type": "integer",
      "nullable": false,
      "metadata": {}
    },
    {
      "name": "Boroght",
      "type": "string",
      "nullable": true,
      "metadata": {}
    },
    {
      "name": "zone",
      "type": "string",
      "nullable": true,
      "metadata": {}
    },
    {
      "name": "serviceZone",
      "type": "string",
      "nullable": true,
      "metadata": {}
    }
  ]
}

验证代码

你原来的代码逻辑是正确的,使用修改后的JSON文件后,执行以下代码应该就能正常生成StructType了:

import org.apache.spark.sql.types._
import scala.io.Source

val schemaSource = Source.fromFile(url.getFile).mkString
val schemaFromJson = DataType.fromJson(schemaSource).asInstanceOf[StructType]

// 可以打印Schema验证结果
println(schemaFromJson.prettyJson)

额外注意事项

如果之后需要定义其他复杂类型或基础类型,记得遵循Spark的DataType JSON规范:

  • 整数类型:"integer"(对应IntType)
  • 长整数类型:"long"(对应LongType)
  • 字符串类型:"string"(对应StringType)
  • 布尔类型:"boolean"(对应BooleanType)
  • 数组类型需要用对象形式定义,比如字符串数组:{"type": "array", "elementType": "string"}
  • 嵌套结构体类型:{"type": "struct", "fields": [...]}(和你顶层的结构一致)

这样修改后,你的代码就能成功解析JSON并生成正确的StructType作为DataFrame的Schema了。

内容的提问来源于stack exchange,提问作者Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 07:57:31