Scala处理复杂json

Scala 处理复杂 json

示例 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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值