Hello,
I need help with resolving implicit JsonFormat.
Here is my code:
package com.mycompany.rest.spray.tags
import com.mycompany.rest.spray.SpringService
import com.mycompany.domain.{User, Tag}
import spray.routing.Directives._
import spray.http.MediaTypes
import spray.json._
import DefaultJsonProtocol._
import scala.collection.immutable
trait TagsService { this: SpringService =>
def tagsRoute(implicit owner: User) =
path("tags") {
get {
respondWithMediaType(MediaTypes.`application/json`) {
complete {
import scala.collection.JavaConversions.asScalaBuffer
val tags: immutable.List[Tag] = asScalaBuffer(someService.findBySearchTerm[Tag]("",
owner.id)).toList // #findBySearchTerm() returns java.util.List (Hibernate). For some reason import scala.collection.JavaConversions._ doesn't work :/
// tags(0).toJson
tags.toJson
}
}
}
}
}
object TagsService {
implicit object TagJsonFormat extends RootJsonFormat[Tag] {
def write(tag: Tag) =
JsObject(
"id" -> JsNumber(
tag.id),
"name" -> JsString(
tag.name),
"desc" -> JsString(tag.description)
)
def read(value: JsValue) = {
value.asJsObject.getFields("id", "name", "desc") match {
case Seq(JsNumber(id), JsString(name), JsString(desc)) => {
val t = new Tag()
t.id = id.toLong
t.name = name
t.description = desc
t
}
case _ => throw new DeserializationException("Tag expected")
}
}
}
}
By defining TagJsonFormat in the companion object I think it should be in scope but it seems it is not.
The error I get is:
Cannot find JsonWriter or JsonFormat type class for List#15168[com#9.mycompany#7199.domain#7217.Tag#28124]
tags.toJson
^
I'm relatively new to Scala and very fresh with Spray-Json.
What I'm doing wrong ?
Thanks!
Daniel