akka-http复杂的json转换

时间:2017-07-13 03:17:36

标签: json akka

我想使用akka http实现一个宁静的http服务。 POST方法接收json params并做某事。

{
    "user": {
        "userid": 123,
        "reqid": "abcdef",
        "username": "张三"
    },
    "article": {
        "atype": 1,
        "fromdate": "2017-06-27"
    },
    "tags": {
        "fixtags": [
            { "t":"t1", "w": 30 },
            { "t":"t2", "w": 20 },
            { "t":"t3", "w": 10 },
            { "t":"t4", "w": 50 }
        ],
        "atags": [
            { "t":"t5", "w": 30 },
            { "t":"t6", "w": 20 }
        ]
    }
}

案例类

case class Article(atype: Int, fromdate: String)
case class Tag(t: String, w: Double)
case class FixTags(fixtags: List[Tag])
case class ATags(atags: List[Tag])
//case class Tags( fixtags: List[Map[String, Float]], atags: List[Map[String, Float]] )
case class Tags(fixtags: FixTags, atags: ATags)

case class AUserInfo(user: User, article: Article, tags: Tags)
implicit val userFormat1 = jsonFormat3( User )
implicit val artFormat1 = jsonFormat2( Article )
implicit val tagFormat1 = jsonFormat2( Tag )
implicit val ftagFormat1 = jsonFormat1( FixTags )
implicit val atagFormat1 = jsonFormat1( ATags )
implicit val tagsFormat1 = jsonFormat2( Tags )

implicit val userFormat = jsonFormat3( AUserInfo )

路线:

path( "rcmd" / LongNumber ) {
            userid =>
                post {


                    entity( as[AUserInfo] ) { userinfo =>do sth}

因为[AUserInfo]会报告错误:

  

请求内容格式错误:       字段中需要的对象' fixtags'%

或:

  

无法找到参数um的隐含值:       akka.http.scaladsl.unmarshalling.Unmarshaller

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我已经弄明白了什么错误: 因为我的json字符串格式不适合我的case类。 我将案例类更改为以下并修复该错误:

//case class FixTags(fixtags: List[Tag])
//case class ATags(atags: List[Tag])

case class Tags(fixtags: List[Tag], atags: List[Tag])