English 中文(简体)
如何在浓缩的基础上动态发送?
原标题:How to dynamically dispatch based on enrichment?
最佳回答

有一种方法, 但是它需要一个 < em> lot < / em > 反射, 因此非常头疼。 基本想法如下。 < code> DefaultJson 协议 对象继承了含有包含 < code> write 方法的隐含物体的一堆特性。 每一个都有一个访问器功能, 但是您不知道它的名称。 基本上, 您会采取没有参数的 < em> all < / em > 方法, 并返回一个具有 < code> write 方法的天体, 该天体可以选择对象的类别, 并返回一个 < code> JsValue 。 如果您找到一个精确的方法返回一个这样的类别, 请使用反省来称呼它。 否则, 保释 。

它看起来像 something like this (警告,未经测试):

def canWriteMe(writer: java.lang.Class[_], me: java.lang.Class[_]): 
  Option[java.lang.reflect.Method] =
{
  writer.getMethods.find(_.getName == "write").filter{ m =>
    classOf[JsValue].isAssignableFrom(m.getReturnType) && {
      val parm = m.getParameterTypes()
      m.length == 1 && parm(0).isAssignableFrom(me)
    }
  }
}
def maybeJson2(any: Any): Option[JsValue] = {
  val couldWork = {
    DefaultJsonProtocol.getClass.getMethods.
      filter(_.getParameterTypes.length==0).
      flatMap(m => canWriteMe(m.getReturnType, any.getClass).map(_ -> m))
  }
  if (couldWork.length != 1) None else {
    couldWork.headOption.map{ case (wrMeth, obMeth) =>
      val wrObj = obMeth.invoke(DefaultJsonProtocol)
      val answer = wrMeth.invoke(wrObj, any)
    }
  }
}

无论如何,你最好一步一步地将REPL中的 DefaultJson Protocol 类分开,找出如何可靠地识别定义作者的物体,然后从中取出 write 方法。

问题回答

我不确定它是否适合你需要, 但这里有另一种方法, 很简单,而且类型安全。

如果您保留参数的类型( 而不是使用 < code> anyny ), 您可以依靠隐含参数分辨率在汇编时间找到正确的转换 :

def toJson[T:JsonFormat]( t: T ): JsValue = implicitly[JsonFormat[T]].write(t)

您不需要选项, 因为程序会在编译时失败, 如果您试图通过一个“ 无法” 的参数 。





相关问题
JQuery/MVC Search Issue

I have inherited a piece of work where the entry screen shows a summary of 20 calculated variables. E.g. Var A (250), Var B (79). Clicking on any of these links takes the user to a view with a ...

jQuery quicksearch plug-in tinkering with JSON

I ve implemented the quicksearch plugin by Rik Lomas and I love it for an application in a custom CMS I m building. I was wondering though, since I m going to have a bizillion items in the table if ...

JSON with classes?

Is there a standardized way to store classes in JSON, and then converting them back into classes again from a string? For example, I might have an array of objects of type Questions. I d like to ...

PHP json_decode question

i m trying to use json_decode to combine a few json objects and then re-encode it. my json looks like: { "core": { "segment": [ { "id": 7, "...

Converting JSON data to Java object

I want to be able to access properties from a JSON string within my Java action method. The string is available by simply saying myJsonString = object.getJson(). Below is an example of what the string ...