带有Play框架的Scala Graph JSON

时间:2016-09-26 12:32:57

标签: json scala playframework-2.0

我正在尝试将POST请求传递给使用Play开发的REST API! (2.5)我想使用Scala Graph的对象(来自图核心依赖)。 看起来这个图已经有了基于lift-json的JSON序列化/反序列化方法,但是我不知道如何插入"插入"进入Play Json库。到目前为止,我使用了隐式转换器(使用Reads / Writes方法),但我想避免为图形部分编写自己的方法,因为它已经是库本身的一部分。

例如,我们说我有这段代码:

import java.util.UUID
import scalax.collection.Graph

case class Task(
  id: UUID,
  status: String)

case class Stuff(
  id: UUID = UUID.randomUUID(),
  name: String,
  tasks: Option[Graph[Task, DiEdge]])

implicit val stuffWrites: Writes[Stuff] = (
    (JsPath \ "id").write[UUID] and
    (JsPath \ "name").write[String]
  )(unlift(Stuff.unapply))

implicit val stuffReads: Reads[Stuff] = (
    (JsPath \ "id").read[UUID] and
    (JsPath \ "name").read[String]
  )(Stuff.apply _)

implicit val taskWrite: Writes[Task] = (
    (JsPath \ "id").write[UUID] and
    (JsPath \ "status").write[String]
  )(unlift(Task.unapply))

implicit val taskReads: Reads[Task] = (
    (JsPath \ "id").read[UUID] and
    (JsPath \ "status").read[String]
  )(Task.apply _)

我错过了序列化图表和育儿的部分。我应该从头开始重写所有内容,还是可以依赖scalax.collection.io.json中的方法toJson / fromJson?

2 个答案:

答案 0 :(得分:1)

由于我努力工作,我想我会分享代码:

class UUIDSerializer extends Serializer[UUID] {
  private val UUIDClass = classOf[UUID]

  def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), UUID] = {
    case (TypeInfo(UUIDClass, _), json) => json match {
      case JString(id) => UUID.fromString(id)
      case x => throw new MappingException("Can't convert " + x + " to UUID")
    }
  }
  def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
    case x: UUID => JString(x.toString)
  }
}

val extraSerializers = new UUIDSerializer :: Nil
implicit val formats = Serialization.formats(NoTypeHints) ++ extraSerializers

val taskDescriptor = new NodeDescriptor[Task](typeId = "Tasks", customSerializers=extraSerializers) {
  def id(node: Any) = node match {
    case Task(id, _) => id.toString
  }
}

val quickJson = new Descriptor[Task](
    defaultNodeDescriptor = taskDescriptor,
    defaultEdgeDescriptor = Di.descriptor[Task]()
)
implicit val tasksWrites = new Writes[Graph[Task, DiEdge]] {
  def writes(graph: Graph[Task, DiEdge]): JsValue = {
    val json = graph.toJson(quickJson)
    Json.parse(json.toString)
  }
}

implicit val tasksReads = new Reads[Graph[Task, DiEdge]] {
  def reads(json: JsValue): JsResult[Graph[Task, DiEdge]] = {
    try {
      val graph = Graph.fromJson[Task, DiEdge](json.toString, quickJson)
      JsSuccess(graph)
    }
    catch {
      case e: Exception =>
        JsError(e.toString)
    }
  }
}

implicit def stuffModelFormat = Jsonx.formatCaseClass[Stuff]

答案 1 :(得分:0)

您可以尝试为您指定格式的案例类编写随播对象。

示例:

object Task {
  implicit val taskModelFormat = Json.format[Task]
}

object Stuff {
  implicit val staffModelFormat = Json.format[Stuff]
}

代替上述implicits。使用此解决方案,编译器将为您解析已知的格式化程序,您可能只需要指定缺失/未知类型而不是整个结构。