我已经获得了以下代码,用于解析以下JSON字符串与Jerkson,杰克逊的Scala包装器:
代码:val vertex = Json.parse[Ranked[UserVertex]](rawString)
Json :"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无法找到该类,但它确实已加载。知道这个的根本原因是什么?我这里有多种类加载器问题吗?谢谢!
答案 0 :(得分: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
使用Play 2.3.5
和Scala 2.11.4