一、背景
昨晚接了一个需求,从kafka里读数据,解析json,然后将json转成相应的格式。【这还不简单,分分钟搞定,然后就有了下面的难点,吼吼吼吼】
二、难点
今天看了一眼数据发现,json数据居然有不确定数量的URL,这咋搞?
数据格式如下:
{"text": "你"}
{"text": "你","url1":"https://nnihl"}
{"text": "你","url1":"https://nnihl","url2":"https://nnihl"}
{"text": "你","url1":"https://nnihl","url2":"https://nnihl","url3":"https://nnihl"}
数据格式解释:
(1)公共相同字段只保存了text,其他省略。
(2)可变json的key,有的没有URL,有的有URL1,有的有URL1,URL2,有的......
三、解决方案
分两次处理数据,第一次fastjson正常解析JSON,第二次,正则表达式,提取出URL。然后将两个合并到一起。
第一次处理:
val postInfo = JSON.parseObject(consumerRecord.value(), classOf[PostInfo])
相关maven:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.74</version>
</dependency>
第二次:
import scala.util.matching.Regex
val pattern = new Regex("(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]")
val str: String = (pattern findAllIn info).mkString("#")
没有maven,在scala的util包里面的。
参考资料:https://www.runoob.com/scala/scala-regular-expressions.html
四、优化思路
感觉这次是碰巧,碰巧可变都是URL,碰巧都是链接,可以这样搞,一旦不是这种,就不太使用。
以后要想办法弄出来一个真正的JSON动态解析。