2017-05-04 48 views
0

轉換我有以下簡單的代碼matcherror例外,而試圖JSON字符串

val fileLine = s"""{"AP_details": [{"MAC_Address": "00:11:74:00:00:00"},{"MAC_Address": "00:11:74:00:00:00"},{"MAC_Address": "00:11:74:00:00:00"}]} 
    """ 
    val jsonAst = fileLine.parseJson 
    import APDetailsJsonProtocol._ 
    jsonAst.convertTo[APDetails] 

的轉換是在另一個文件中定義爲

封裝測試 進口spray.json._ 進口DefaultJsonProtocol._

case class APDetails(val mAPRadioOperatingParams:List[APDetail]) 
case class APDetail(val mac_id:String) 

object APDetailsJsonProtocol extends DefaultJsonProtocol { 
    implicit val APDetailFormat = jsonFormat1(APDetail) 
    implicit object APDetailsJsonFormat extends RootJsonFormat[APDetails] {  
    def write(c: APDetails) = ??? 
    def read(value: JsValue) = value.asJsObject.getFields("AP_Details") match 
    {    
     case Seq(jsv) => new APDetails(jsv.convertTo[List[APDetail]])    
    } 
    } 
} 

但是,我得到以下例外

Exception in thread "main" scala.MatchError: Vector() (of class scala.collection.immutable.Vector) 
    at test.APDetailsJsonProtocol$APDetailsJsonFormat$.read(APDetails.scala:13) 
    at test.APDetailsJsonProtocol$APDetailsJsonFormat$.read(APDetails.scala:11) 
    at spray.json.JsValue.convertTo(JsValue.scala:31) 
    at test.bootStrap.<init>(bootStrap.scala:25) 
    at test.TestApp$.delayedEndpoint$test$TestApp$1(TestApp.scala:10) 
    at test.TestApp$delayedInit$body.apply(TestApp.scala:4) 
    at scala.Function0$class.apply$mcV$sp(Function0.scala:34) 
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12) 
    at scala.App$$anonfun$main$1.apply(App.scala:76) 
    at scala.App$$anonfun$main$1.apply(App.scala:76) 
    at scala.collection.immutable.List.foreach(List.scala:381) 
    at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35) 
    at scala.App$class.main(App.scala:76) 
    at test.TestApp$.main(TestApp.scala:4) 
    at test.TestApp.main(TestApp.scala) 

我在做什麼錯? 最好的問候, Vishal

回答

0

您在您的Json "AP_details"。你正在做一個getFields("AP_Details")

注意small ddetailsDetailscapital D。這導致一個空的Vector。但是你還沒有處理空矢量的情況,因此你的匹配失敗了,這會給你一個匹配錯誤。

現在...一旦你刪除這個問題,那麼你有另一個問題照顧。

所以,你有一個,

case class APDetail(val mac_id:String) 

然後你像這樣定義的JsonFormat,

implicit val APDetailFormat = jsonFormat1(APDetail) 

現在...這將期望的Json有確切的字段名,其是mac_id每個APDetail但您的Json有MAC_Address。所以這不適合你。

所以,你必須先解決您的案例類(或爲其提供適當的JsonFormat),

case class APDetail(Mac_Address: String) 

現在...有你read另一個問題,它應該是這樣的,

def read(value: JsValue) = value.asJsObject.getFields("AP_details") match {    
    case Seq(jsv): Seq[JsArray] => new APDetails(jsv.convertTo[List[APDetail]])    
} 
+0

魔鬼在'Details' ... –