2015-05-06 29 views
1

我寫一個Json的解析爲一個休息web服務的響應,我有一個JSON文件爲尋找:播放ScalaJSON讀[T]解析

{"program": { 
       "name": "myname", 
       "@id": "12345", 
       "$": "text text text" 
      }, etc. etc. 

我寫了一個case類的讀取對象:

case class program(name:String) 

implicit val programFormat = Json.format[program] 

而對於獲得此數據的僞代碼:

val x=(jobj \ "program").validate[program] 

x match { 
    case JsSuccess(pr, _) => println("JsSuccess:"+pr) 
     for(p<- pr.program) 
     { 
      println(p.name) 
     } 
    case error: JsError => .... 
} 

對於字段名沒有問題,代碼工作很好,但我不明白^ h ow捕獲字段「@id」和字段「$」,因爲我無法在名爲@id或$的類中創建一個參數。

謝謝你的幫助。在我看來

回答

4

更正確的解決方案是創建自己的Reads,那就是:

case class Program(name: String, id: String, dollar: String) 
implicit val programWrites: Reads[Program] = (
     (__ \ "name").read[String] ~ 
     (__ \ "@id").read[String] ~ 
     (__ \ "$").read[String] 
)(Program.apply _) 

文檔:https://www.playframework.com/documentation/2.4.x/ScalaJsonCombinators#Reads

另一種解決方案,我認爲更糟糕的一個,是使用反引號簽署

case class Program(name: String, `@id`: String, `$`: String) 
implicit val programFormat = Json.format[Program] 

它允許在方法名稱,字段名稱等中寫入特殊符號。 關於它的更多信息:Need clarification on Scala literal identifiers (backticks)