2015-04-22 71 views
4

我试图连载GeneralResponse杰克逊映射器在Scala中的泛型类

case class GeneralResponse[T](succeeded: Boolean, payload: Option[T]) 

和有效载荷为GroupsForUserResult

case class GroupsForUserResult(groups: Seq[UUID]). 

我使用mapper.readValue(response.body, classOf[GeneralResponse[GroupsForUserResult]]),但不幸的是,有效载荷序列化为Map而不是所期望的案例类别(GroupForUserResult)。

回答

4

因为Java擦除 - 杰克逊无法知道有关从线一般类型T的运行时 -

mapper.readValue(response.body, classOf[GeneralResponse[GroupsForUserResult]]) 

解决这一问题将是

mapper.readValue(json, new TypeReference[GeneralResponse[GroupsForUserResult]] {}) 

这样你提供具有所有需要的类型信息的TypeReference的实例。

+0

太棒了!谢谢! – Gal

+1

它不适用于我的情况。具有'case InputMessage [+ S <:Storage,+ P <:Partitioning](fromView:View [S,P],toView:View [S,P],partition:Partition)'和'ObjMapper.readValue [InputMessage [ S3Storage,TimePartitioning]](inputMsg,new TypeReference [InputMessage [S3Storage,TimePartitioning]](){})'我仍然收到错误 – lisak

1

接受的答案是非常接近,但你也必须提供类型参数.readValue方法,

工作示例与测试,

import com.fasterxml.jackson.core.`type`.TypeReference 
import com.fasterxml.jackson.databind.ObjectMapper 
import com.fasterxml.jackson.module.scala.DefaultScalaModule 
import org.scalatest.{FunSuite, Matchers} 

case class Customer[T](name: String, address: String, metadata: T) 

case class Privileged(desc: String) 

class ObjectMapperSpecs extends FunSuite with Matchers { 

    test("deserialises to case class") { 

    val objectMapper = new ObjectMapper() 
     .registerModule(DefaultScalaModule) 

    val value1 = new TypeReference[Customer[Privileged]] {} 

    val response = objectMapper.readValue[Customer[Privileged]](
     """{ 
      "name": "prayagupd", 
      "address": "myaddress", 
      "metadata": { "desc" : "some description" } 
     } 
     """.stripMargin, new TypeReference[Customer[Privileged]] {}) 

    response.metadata.getClass shouldBe classOf[Privileged] 
    response.metadata.desc shouldBe "some description" 
    } 

} 

com.fasterxml.jackson.databind.ObjectMapper#readValue签名,

public <T> T readValue(String content, TypeReference valueTypeRef) 
    throws IOException, JsonParseException, JsonMappingException 
{ 
    return (T) _readMapAndClose(_jsonFactory.createParser(content), _typeFactory.constructType(valueTypeRef)); 
} 

如果你没有提供类型参数,它会炸毁错误Customer cannot be cast to scala.runtime.Nothing$