【问题标题】:Strange generic method behaviour奇怪的泛型方法行为
【发布时间】:2017-10-20 13:41:27
【问题描述】:

这行得通:

val rpcResponse = Serialization.read[RPCResponse[Map[String, Double]]](call("listaccounts"))

但是这个

val rpcResponse:RPCResponse[Map[String, Double]] = Serialization.read(call("listaccounts"))

给我一​​个例外:

MappingException: Parsed JSON values do not match with class constructor args=
arg types=
executable=Executable(Constructor(public scala.runtime.Nothing$()))
cause=null
types comparison result=

两种结构不应该以相同的方式工作吗?

编辑:

示例案例类:

case class AA[R](f1: String, f2: R)

和代码:

val rpcResponse: AA[Map[String, Double]] = Serialization.read(
  """
    |{
    | "f1": "fff",
    | "f2": {
    |       "a":1,
    |       "b":2
    |     }
    |}
  """.stripMargin)

println(rpcResponse)

【问题讨论】:

  • 请提供您用于转换等的案例类
  • @Pavel:给你
  • 我会假设你在提到 RPCResponse 时使用的是 scala-json-rpc ?
  • @Pavel:不。为什么你认为这很重要?
  • 好吧,我正在尝试在本地复制这个问题,在 json4s 中的任何地方都找不到 RPCResponse

标签: scala json4s


【解决方案1】:

据我了解,您需要指定默认的 json 格式化程序。 下一个代码对我来说很好:

import org.json4s.native.Serialization  
implicit val formats = org.json4s.DefaultFormats

case class RPCResponse[R](f1:String, f2:R)

val rpcResponse:RPCResponse[Map[String, Double]] = Serialization.read[RPCResponse[Map[String, Double]]](
  """
    |{
    | "f1": "fff",
    | "f2": {
    |       "a":1,
    |       "b":2
    |     }
    |}
  """.stripMargin)

println(rpcResponse)

【讨论】:

  • 你改变了: val rpcResponse:RPCResponse[Map[String, Double]] = Serialization.read 到 val rpcResponse = Serialization.read[RPCResponse[Map[String, Double]]] 这是主题问题
  • 是的。次要,但第二行代码也适用于我!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 1970-01-01
  • 2019-05-25
  • 2021-01-25
相关资源
最近更新 更多