【发布时间】:2016-06-21 07:36:46
【问题描述】:
首先 - 抱歉这个愚蠢的问题。 我从 DB 得到了一些 Json 字符串,想用 json4s 解析所有字符串:
val df = sqlContext.sql("SELECT * FROM analytic.test").repartition(22)
val df_base = df.map(f => {
implicit val formats = DefaultFormats
val jsonString = f(5).toString
val tempJSON = parse(jsonString)
val mainJsonArray = tempJSON \ "events"
(
f(2).toString,
makeEventArray(mainJsonArray)
)
}).cache()
很好,我得到了 Json,但有时在 DB 中会出现一些失败的 Json,这会让我出错:
com.fasterxml.jackson.core.JsonParseException: Unexpected end-of-input: was expecting closing '"' for name
第一个问题 - 如何使用损坏的 Json 避开这一行并继续我的程序?
我尝试用 try\catch 包围 parse,但在这种情况下:
var tempJSON = json4s.JsonAST.JValue
try {
tempJSON = parse(f(5).toString)
} catch {
case e: Exception => println("Error on JSON parser. " + e )
}
但出现错误:
Error:(51, 25) type mismatch;
found: org.json4s.JValue (which expands to) org.json4s.JsonAST.JValue
required: org.json4s.JsonAST.JValue.type tempJSON = parse(f(5).toString)
^
第二个问题 - 如何正确声明 tempJson?
或者我必须在解析之前验证 Json?怎么样?
【问题讨论】:
标签: json scala try-catch json4s