I have a converter function that creates a case class object from JSON, which is defined as follows:
object JSONConverter {
import language.experimental.macros
def modelFromJson[T <: Model](json: JsValue):T = macro modelFromJson_impl[T]
}
I'm interested in creating the same object from a String that contains JSON, too. So I have overloaded the original method by changing the above snippet as follows:
object JSONConverter {
import language.experimental.macros
// Using Play Framework library to parse a String to JSON
def modelFromJson[T <: Model](json: JsValue):T = macro modelFromJson_impl[T]
def modelFromJson[T <: Model](jsonString: String):T = {
val json: JsValue = Json.parse(jsonString)
modelFromJson[T](json)
}
}
But I get this error message:
[error] ... not found: value T
[error] modelFromJson[T](json)
[error] ^
So for the following configuration
case class User(name: String, age: Int, posts:String, score: Double, lastLogin: DateTime) extends Model
// First case
JSONConverter.modelFromJson[User](someJsValueObject)
// Second case
JSONConverter.modelFromJson[User](someJsonString)
The macro tries to return the following expressions:
User.apply(json.$bslash("name").as[String], json.$bslash("age").as[Int], json.$bslash("posts").as[String], json.$bslash("score").as[Double], new DateTime(json.$bslash("lastLogin").as[Long]))
T.apply()
The first one is correct, while the second one tries to access T instead.
The macro is basically implemented as follows:
def modelFromJson_impl[T: c.WeakTypeTag](c: Context)(json: c.Expr[JsValue]): c.Expr[T] = {
import c.universe._
val tpe = weakTypeOf[T]
// Case class constructor
val generation = Select(Ident(newTermName(tpe.typeSymbol.name.decoded)), newTermName("apply"))
// Generate stuff like json.\("fieldName").as[String]
val fields = tpe.declarations collect {
...
}
val s = Apply(generation, fields.toList)
// Display results above for debugging
println(show(s))
c.Expr[T](s)
}
Is it possible to achieve what I want without making another macro?
Thanks very much in advance!