示例 JSON 如下
{
"nodeName": "xxx",
"source": "join",
"left_child": {
"nodeName": "yyy",
"join": null,
"source": "hive",
"parameter": {
"address": "",
"port": 9083,
"database": "",
"table": "",
"condition": "id>1"
},
"columns":[
{
"name": "id",
"type": "int",
"index": 1
},
{
"name": "",
"type": "",
"index": 2
}
],
"transformer": {
"name": "xxx",
"parameter":
{
"function": "substring",
"columnIndex": 1,
"paras": [0,3]
}
}
}
}
在pom.xml文件中添加 fastjson 依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
并导入包
import com.alibaba.fastjson.{JSON, JSONArray, JSONObject}
//String类型的json,json过长请自行压缩粘贴
val jSON = ""
//将json String转换成JSONObject
val JSONObj: JSONObject = JSON.parseObject(jSON)
//获取columnIndex的值
val columnIndex: Int = JSONObj.getJSONObject("right_child").getJSONObject("transformer").getJSONObject("parameter").get("columnIndex").toString.toInt
//从JSONObject中开始一层一层取对象,最后把paras获取为数组
val paras: Array[AnyRef] = JSONObj.getJSONObject("right_child").getJSONObject("transformer").getJSONObject("parameter").getJSONArray("paras").toArray()
//拿到json中 column数组中的字段名
//获取columns中的内容转为数组,并获取数组第一个内容
val jsonArray: JSONArray = JSONObj.getJSONObject("left_child").getJSONArray("columns")
val colObj: JSONObject = jsonArray.getJSONObject(0)
//获取colObj对象里的key,为方便处理转为数组
val colNames: util.Set[String] = colObj.keySet()
val array: Array[AnyRef] = colNames.toArray
//将数组转为字符串
val str: String = array.mkString(",")
运行结果:name,index,type