定義爲List [A]的JSON元素B,我無法將List[A]
編組爲適當的Json(對象數組)。我使用的是AKKA-Http和Spray-Json。無法使用標題中所述的AKKA-Http和Spray-Json
我定義了兩個case類:
final case class Item(id: String, pid: String, title: String)
final case class Items(items: List[Item])
而對通話GET http://localhost:8080/item
接受:
class ItemEndpoint extends Directives with ItemJsonSupport {
val route: Route = {
path("item") {
get {
parameters("page".?, "size".?) {
(page, size) => (page, size) match {
case (_, _) =>
onSuccess(Server.requestHandler ? GetItemsRequest){
case response: Items =>
complete(response)
case _ =>
complete(StatusCodes.InternalServerError)
}
}
}
}
}
}
}
GetItemsRequest
被調用。後者被定義爲
case class GetItemsRequest
而經由RequestHandler
作爲
class RequestHandler extends Actor with ActorLogging {
var items : Items = _
def receive: Receive = {
case GetItemsRequest =>
items = itemFactory.getItems
sender() ! items
}
}
凡getItems
執行對Cassandra
查詢Spark
def getItems() : Items = {
val query = sc.sql("SELECT * FROM mydb")
Items(query.map(row => Item(row.getAs[String]("item"),
row.getAs[String]("pid"), row.getAs[String]("title")
)).collect().toList)
}
返回Items
含有List[Item]
。所有的對象都打印正確(其中一些具有空字段)。
使用ItemJsonFormatter
trait ItemJsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
implicit val itemFormat: RootJsonFormat[Item] = jsonFormat3(Item)
implicit val itemsFormat: RootJsonFormat[Items] = jsonFormat1(Items)
}
導致以下錯誤:
[simple-rest-system-akka.actor.default-dispatcher-9] [akka.actor.ActorSystemImpl(simple-rest-system)] Error during processing of request: 'requirement failed'. Completing with 500 Internal Server Error response. To change default exception handling behavior, provide a custom ExceptionHandler. java.lang.IllegalArgumentException: requirement failed
我試圖抓住它的異常和工作,但我還沒有得到關於該問題的更多英特爾。
我在編組上跟着AKKA DOCS。
當做同樣的事情,但只得到1項,它工作得很好,我得到一個JSON包含所有Item
的參數格式良好。
{
"id": "78289232389",
"pid": "B007ILCQ8I",
"title": ""
}
即使尋找其他相關Q/A我無法找到答案,所以 什麼造成的?我該如何解決它?
我無法測試它,因爲我有一些版本問題有相關性。如果有效,它將很快接受。無論如何,我不明白爲什麼單個項目不會發生這個問題。即使我有一些空的領域,當我做一個單一的我沒有錯誤。任何想法? – AndreaM16
在你的例子中,只有一個'Item',''title''字段的值看起來是一個空字符串,而不是空字符串。 – chunjef