我正在将地理网格滚动到一个现有的大型Scala项目中。我将使用它来处理GeoJson。 Geotrellis取决于spray
。
现有项目将json4s
用于内置在伴随对象的.apply()
方法中的json解析器,以处理一些繁重的数据结构。
因此geotrellis / spray将处理GeoJson / Features ...,但我想使用现有的基于json4s的解析器将properties
解析为数据结构。
一个最小示例...从此处修改:https://geotrellis.readthedocs.io/en/latest/guide/vectors.html#deserializing-from-geojson
这很好(所有地理网格/喷雾)...
import geotrellis.vector.{Feature, Point, PointFeature, Polygon, PolygonFeature}
import geotrellis.vector.io._
import geotrellis.vector.io.json._
import spray.json.DefaultJsonProtocol._
// !!! REPLACE THIS PART (MyData & md) !!!
// data structure and parser for "properties" => MyData
case class MyData(d1: Int, d2: String, d3: Option[Double]=None)
implicit val md: spray.json.RootJsonFormat[MyData] = jsonFormat3(MyData)
// json as string
val json: String =
"""{"type":"Feature","geometry":{"type":"Point","coordinates":[0.0,0.0]},"properties":{"d1":123,"d2":"xyz"}}"""
// parsed
val point_feature = json.parseGeoJson[Feature[Point, MyData]]
但是...现在我想扔掉MyData
和md
(案例类无法满足我的需要),并找到一种使用现有数据结构和解析器的方法。对于这个玩具示例,它模仿了我正在使用的东西...
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods.{render,compact,pretty}
import org.json4s.DefaultFormats
import org.json4s.jackson.JsonMethods._
import org.json4s.{JValue, JObject, JInt, JDouble, JString}
import scala.util.Try
class MyData2(val d1: Int, val d2: String, val d3: Option[Double]) {
def json: JObject = (
("d1" -> d1) ~
("d2" -> d2) ~
("d3" -> d3)
)
}
object MyData2 {
// json => MyData2
def apply(json: String): MyData3 = {
implicit val formats = DefaultFormats
val parsedJson: JValue = parse(json)
val d1: Int = (parsedJson \ "d1").asInstanceOf[JInt].num.toInt
val d2: String = (parsedJson \ "d2").asInstanceOf[JString].s
val d3: Option[Double] = Try { (parsedJson \ "d3").asInstanceOf[JDouble].num.toDouble }.toOption
new MyData2(d1, d2, d3)
}
}
我的问题是...
如何使用现有的MyData2.apply()
来解析properties
中的json
?
我去看了看这里:https://github.com/spray/spray-json/blob/master/src/main/scala/spray/json/StandardFormats.scala
我当时想也许可以扩展RootJsonFormat
并尝试通过json4s
和spray
方法将read
的值转换为write
……但是我必须认为有一种更简单的方法。
谢谢。