2

我有以下代码,用于使用Jerkson(Jackson 的 Scala 包装器)解析以下 JSON 字符串:

代码val vertex = Json.parse[Ranked[UserVertex]](rawString)

杰森"originalPos":"515693049","rankScore":1.2409032357406248E8,"ranked":{"userId":"101010110","userName":"John","channel":"thirtyfive"}}

下面的 JSON 由这个 Scala 类表示:

case class Ranked[T] (
  val originalPos: String,

  val rankScore: Double,

  val ranked: T
)

T 是一个UserVertex类,上面有以下字段(userId、userName、channel)。当我尝试解析 JSON 字符串时,出现以下错误:

[error] application - Could not parse the string:
{"originalPos":"655330261","rankScore":1.2423105672295567E8,"ranked":{"userId":"655330261","userName":"Sheile Mercado-Mallari","channel":"facebook"}}
java.lang.ClassNotFoundException: T
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at com.codahale.jerkson.util.CaseClassSigParser$.loadClass(CaseClassSigParser.scala:153)

看起来 ClassLoader 找不到该类,但它肯定已加载。知道这是什么根本原因吗?我这里有某种多类加载器问题吗?谢谢!

4

1 回答 1

1

在这种情况下(通用案例类),您需要定义您的阅读器(这是 Play 中的已知约束)

case class UserVertex(userId:String, userName: String, channel: String)
case class Ranked[T](originalPos: String, rankScore: Double, ranked: T)

请注意,案例类中不需要val关键字,因为它将通过使用case关键字自动提供。

import play.api.libs.json._
import play.api.libs.functional.syntax._

implicit def vertexReader: Reads[UserVertex] = Json.reads[UserVertex]

implicit def rankedReader[T](implicit reads: Reads[T]): Reads[Ranked[T]] = (
    (__ \ "originalPos").read[String] ~ 
    (__ \ "rankScore").read[Double] ~ 
    (__ \ "ranked").read[T]
    )(Ranked.apply[T] _)

现在您可以将以下原始 json 转换为Ranked

val rawString =
    """{
      |  "originalPos": "515693049",
      |  "rankScore": 1.2409032357406248E8,
      |  "ranked": {
      |    "userId": "101010110",
      |    "userName": "John",
      |    "channel": "thirtyfive"
      |  }
      |}""".stripMargin

使用以下代码

val rankedJson = Json.parse(rawString)
val ranked = Json.fromJson[Ranked[UserVertex]](rankedJson).get

免责声明

用 Play2.3.5和 Scala测试2.11.4

于 2014-11-05T05:55:39.847 回答