0

我知道有一个类似 api 的 xpath 可以从 Json4s 中的 JObject 中获取字段

val x = (obj \ "Type").asInstanceOf[JString].values

但是感觉有点麻烦,我不喜欢 api 之类的符号。我有点想要这样的东西:

implicit class JsonExtensions(json: JObject) {

  def get[T <: JValue](key: String) : T.Values = {
     (json \ key).asInstanceOf[T].values
  }
}

并像这样使用它

val x  = obj.get[String]("type")

但是它不能编译,T 的上限是一个 JValue,所以 Id 希望能够引用所有 JValue 上的类型成员 Values。作为参考,他是 JValue 的狙击手:

sealed abstract class JValue extends Diff.Diffable with Product with Serializable {
    type Values
    def values: Values
...
}

我是 scala 的新手,我怎样才能让编译器满意?

4

1 回答 1

0

Here is the solution if anyone is interested:

implicit class JsonExtensions(json: JValue) {

  def get[T <: JValue](key: String) : T#Values = {
    (json \ key).asInstanceOf[T].values
  }
}

val x = obj.get[JString]("type")

You have to specify the expected type but x will the underlying Values of the Json Ast type. So for JString is a string, for JObject its a Map[String,Any]

Thank you insan-e

于 2017-11-03T11:51:57.183 回答