user461697
user461697

Reputation:

Get JsonSubType array contents in Scalatra project

I'm using JsonSubTypes (com.fasterxml.jackson.annotation.JsonSubTypes) in a Scalatra project and wanted to have a method either in the ProblemFactory class below or the servlet which returns a list of the "name"s in the 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 {

I've played around the reflection a bit, but can't seem to extract the names:

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

Upvotes: 1

Views: 202

Answers (1)

Nate
Nate

Reputation: 2205

I wouldn't use Scala reflection for this. Instead do what Jackson does:

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()))
  }
}

This gives the output:

addition
evenodd

Upvotes: 1

Related Questions