Following on from:
Scala classOf for type parameter
I've tried implementing it but seem to get some weird generics problem, actually I've muddled my way through a couple of them now, but this is as close to correct I can get it...
I'm using the Scala - Jackson JSON bindings (excellent lib by the way, much easier than SJson)
def genparseResult[T: ClassManifest](t: T,s:String):Either[Tuple2[JsonParseException,String],T] = {
try{
val res = jsonSerializer.readValue(s, classManifest[T].erasure)
Right(res)
}
catch{
case jpe:JsonParseException => Left((jpe,s))
}
}
Anyhow, the code above is generating the following compile error:
type mismatch; found : res.type (with underlying type Any) required: T
I'm confused as hell. Should the code above be able to work?
Update following input from tenshi, I post the completed class
import com.fasterxml.jackson.core.JsonParseException
object DatasiftJsonMapper {
import java.util.Date
import com.fasterxml.jackson.databind.{ Module, ObjectMapper }
import com.fasterxml.jackson.module.scala.DefaultScalaModule
val jsonSerializer = {
val m = new ObjectMapper()
m.registerModule(DefaultScalaModule)
m
}
def parseDSResult(s: String): Either[Tuple2[JsonParseException, String], DatasiftResult] = {
genparseResult(classOf[DatasiftResult], s)
}
def parseQRegRequest(s: String): Either[Tuple2[JsonParseException, String], QRegRequest] = {
genparseResult(classOf[QRegRequest], s)
}
def genparseResult[T: ClassManifest](t: Class[T], s: String): Either[Tuple2[JsonParseException, String], T] = {
try {
val res = jsonSerializer.readValue(s, classManifest[T].erasure).asInstanceOf[T]
Right(res)
} catch {
case jpe: JsonParseException => Left((jpe, s))
}
}
}
As far as I remember, classManifest[T].erasure
returns Class[_]
instead of Class[T]
, so the result of jsonSerializer.readValue(...)
would be or type Any
. You can try to cast parsing result:
val res = jsonSerializer.readValue(s, classManifest[T].erasure).asInstanceOf[T]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.