在Scalatra项目中获取JsonSubType数组内容

时间:2014-10-21 12:56:23

标签: scala jackson

我在Scalatra项目中使用JsonSubTypes(com.fasterxml.jackson.annotation.JsonSubTypes),并希望在下面的ProblemFactory类或者返回“name”列表中的servlet中有一个方法。 JsonSubTypes Array。

   @JsonTypeInfo(
      use = JsonTypeInfo.Id.NAME,
      include = JsonTypeInfo.As.PROPERTY,
      property = "type")
    @JsonSubTypes(Array(
      new Type(value = classOf[AdditionProblemFactory], name = "addition"),
      new Type(value = classOf[EvenOddProblemFactory], name = "evenodd")
    ))
    abstract class ProblemFactory {

我已经玩了一些反思,但似乎无法提取名字:

ru.typeOf[ProblemFactory].typeSymbol.asClass
.annotations
.find(a => a.tree.tpe == ru.typeOf[JsonSubTypes])

1 个答案:

答案 0 :(得分:2)

我不会为此使用Scala反射。而是做杰克逊所做的事情:

object Test {
  @JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type")
  @JsonSubTypes(Array(
    new Type(value = classOf[AdditionProblemFactory], name = "addition"),
    new Type(value = classOf[EvenOddProblemFactory], name = "evenodd")
  ))
  abstract class ProblemFactory

  class AdditionProblemFactory extends ProblemFactory
  class EvenOddProblemFactory extends ProblemFactory

  def main(args: Array[String]): Unit = {
    val introspector = new JacksonAnnotationIntrospector
    val ac = AnnotatedClass.construct(classOf[ProblemFactory], introspector, null)
    val types = ac.getAnnotations.get(classOf[JsonSubTypes]).value()
    types.foreach(typ => println(typ.name()))
  }
}

这给出了输出:

addition
evenodd