首页 > 解决方案 > Json Parser 不能在 scala 中的高阶函数中工作?

问题描述

我有一个 dstream 并尝试使用 play json 库将每个字符串解析为一个对象。它在外部起作用,但在内部不起作用。它说没有找到隐含。

val textStream: ReceiverInputDStream[String] = streamingContext.socketTextStream("localhost",12345)

textStream.map{record=>
  Json.parse(record).as[Car] //this doesn't works, it shows as: Json.parse(record).as[Car](...)

}

这在 Car 的伴随对象中定义:

object Car {
implicit val carFormat = Json.format[Car]
}

它在内部显式给出隐式时起作用,这似乎有点奇怪。

 textStream.map{record=>
  implicit val carFormat = Json.format[Car] //How do I avoid this
  Json.parse(record).as[Car]
}

我如何避免定义内部并通过定义外部隐含来使其工作?
我也尝试在伴生对象中导入显式,但它没有任何区别。

标签: jsonscalaapache-sparkplayframeworkplay-json

解决方案


推荐阅读