GeoTrellis / Scala:找到Json解析所缺少的隐式证据

时间:2018-09-17 18:02:31

标签: scala implicit spray-json geotrellis

需要哪些输入来定位隐式证据以编译GeoTrellis对GeoJson.parse的调用?

geotrellis.vector.io.json.Geometry使用spray.json进行解析,并且必须能够找到以WithCrs和Geometry类为模板的JsonReader或JsonFormats实例。

证据在FeatureFormats中定义;但是下面的代码片段如何使用它?

以下内容无法解决证据:

  1. 导入geotrellis.vector.io.json.*包中的所有内容
  2. 具体导入隐式import geotrellis.vector.io.json.Implicits
  3. 直接导入FeatureFormats import geotrellis.vector.io.json.FeatureFormats
  4. 确保正确导入,尤其是没有com.vividsolutions.jts.Geometry的导入会掩盖目标对象

这是有问题的代码

import geotrellis.vector.Geometry
import geotrellis.proj4.CRS
import geotrellis.vector.io.json.*
import geotrellis.vector.io.json.{GeoJson, WithCrs}
import org.json4s.{DefaultFormats, Formats}
import scala.util.{Failure, Success, Try}
val exampleQueryJson =
  """
|{
|   "type": "Polygon",
|   "crs": {
|       "type": "name",
|       "properties": {
|           "name": "EPSG:4326"
|       }
|   },
|   "coordinates": [
|       [
|           [....]
|       ]
|   ]
|}
  """.stripMargin

class GeometryReader extends FeatureFormats {
  implicit val jsonFormats: Formats = DefaultFormats
}

object GeometryReader {

  def parseGeometry(request: String): Geometry = {

    GeoJson.parse[Geometry](request)
  }
}

val g = GeometryReader.parseGeometry(exampleQueryJson)

编译错误表明在当前可用的条件下无法找到正确的证据

[error] /path/redacted/GeometryReader.scala:19: Cannot find JsonReader or JsonFormat type class for geotrellis.vector.io.json.WithCrs[geotrellis.vector.Geometry]
[error]       val geometryWithCrs: WithCrs[Geometry] = GeoJson.parse[WithCrs[Geometry]](request)
[error]                                                                                ^
[error] /path/redacted/GeometryReader.scala:25: Cannot find JsonReader or JsonFormat type class for geotrellis.vector.Geometry
[error]       Try(GeoJson.parse[Geometry](request)) match {
[error]                                  ^
[error] two errors found
[error] (compile:compileIncremental) Compilation failed

1 个答案:

答案 0 :(得分:0)

简短答案:添加

import geotrellis.vector.io._

此库的创建者使用包对象来发布这些隐式对象。包对象(下面的源代码)扩展了g.io.json.Implicits,并将它们带入范围。

https://github.com/locationtech/geotrellis/blob/master/vector/src/main/scala/geotrellis/vector/io/package.scala

有关包对象的更多信息:

https://www.scala-lang.org/docu/files/packageobjects/packageobjects.html