2017-07-27 37 views
1

定義爲List [A]的JSON元素B,我無法將List[A]編組爲適當的Json(對象數組)。我使用的是AKKA-HttpSpray-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我無法找到答案,所以 什麼造成的?我該如何解決它?

回答

1

All the objects are printed correctly (some of them have null fields).

唯一的例外可能是因爲getItems將返回Item對象有一個或多個空字段值被拋出。處理這種

一種方法是用空字符串替換空值:

def rowToItem(row: Row): Item = { 
    Item(Option(row.getAs[String]("item")).getOrElse(""), 
     Option(row.getAs[String]("pid")).getOrElse(""), 
     Option(row.getAs[String]("title")).getOrElse("")) 
} 

def getItems(): Items = { 
    val query = sc.sql("SELECT * FROM mydb") 
    Items(query.map(row => rowToItem(row)).collect().toList) 
} 
+0

我無法測試它,因爲我有一些版本問題有相關性。如果有效,它將很快接受。無論如何,我不明白爲什麼單個項目不會發生這個問題。即使我有一些空的領域,當我做一個單一的我沒有錯誤。任何想法? – AndreaM16

+0

在你的例子中,只有一個'Item',''title''字段的值看起來是一個空字符串,而不是空字符串。 – chunjef

相關問題