Akka HTTP如何映射自定义Json

时间:2017-06-03 18:05:57

标签: json scala akka-http

我正在尝试将spary上写的服务转换为akka http,我面临的挑战是将JSON实体映射到案例类

case class Job( id:Option[Long],
                desc :String,
                properties :Seq[Properties],
                configuration : Map[String,JSONString])

case class Properties(jobName:String , type:String)

class JSONString,其中定义了自定义序列化

import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization.write


case class JSONString(string: String) {
  override def toString: String = string

  def toSeq: Seq[String] = {
    // transfors string of the form "[\"prop1\",\"prop2\"]" in a Seq
    string.drop(1).dropRight(1).replaceAll("\"", "").split(",").toSeq
  }
}

class JSONStringSerializer extends CustomSerializer[JSONString](format => ( {
  case obj: JObject => new JSONString(write(obj)(implicitly(DefaultFormats + new JSONStringSerializer)))
  case obj: org.json4s.JsonAST.JNull.type => new JSONString(null)
  case obj: JArray => new JSONString(write(obj)(implicitly(DefaultFormats + new JSONStringSerializer)))
  case s: JString => new JSONString(s.s)
  case i: JInt => new JSONString(i.num.toString())
  case b: JBool => new JSONString(b.value.toString())
}, {
  case x: JSONString =>
    if (x.string == null) {
      new JString("")
    } else if (x.string.contains("[") && x.string.contains("{")) {
      parse(x.string)
    } else if (x.string.equals("true") || x.string.equals("false")) {
      new JBool(x.string.toBoolean)
    } else {
      new JString(x.string)
    }
}
)) {
}

我的特质看起来像

import org.json4s.{DefaultFormats, Formats}
import spray.httpx.Json4sJacksonSupport 

trait JobSerializer extends Json4sJacksonSupport {

  implicit val json4sJacksonFormats: Formats = DefaultFormats + new JSONStringSerializer()
   }

我的工作班就像

class JobSubmitRoute(val localJobService:LocalJob )(implicit executionContext: ExecutionContext) extends  JobSerializer {

  import localJobService._

  val route = (path(HttpConstant.JobServicePath) & post) {
    entity(as[JobDefinition]) { jobDefinition: JobDefinition =>
      complete(submit(jobDefinition))
    }
  } 
}

我尝试使用Json4sSupportJacsonSupport代替JobSerializer https://github.com/hseeberger/akka-http-json进行扩展 但它会产生错误

Error:(24, 14) could not find implicit value for parameter um: akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller[com.models.service.JobDefinition]
    entity(as[JobDefinition]) { jobDefinition: JobDefinition =>

如何将JSON解组为所需的案例类?

0 个答案:

没有答案