2017-02-20 144 views
1

我有一個角度的應用程序,發送到服務器的請求,像這樣:Scala如何將JsonAST.JValue轉換爲類型?

$scope.downloadPartDetails = (parts, e) -> 
    req = { 
     method: 'POST', 
     url: '/downloads/partdetails', 
     headers: { 
     'Content-Type': "application/json; charset=utf-8" 
     }, 
     data: { parts: [ 
     {manufacturer: "mfr1", partNumber: "part num1"}, 
     {manufacturer: "mfr2", partNumber: "part num2"}, 
     {manufacturer: "mfr3", partNumber: "part num3"} 
     ] } 
    } 
    $http(req) 

它顯示了在服務器上是這樣的:

JArray(List(JObject(List(JField(manufacturer,JString(mfr1)), JField(partNumber,JString(part num1)))), JObject(List(JField(manufacturer,JString(mfr2)), JField(partNumber,JString(part num2)))), JObject(List(JField(manufacturer,JString(mfr3)), JField(partNumber,JString(part num3)))))) 

有沒有辦法將其轉換爲一個列表[部分]?

case class Part(mfr: String, pn: String) 

回答

1

如果在JSON和的情況下類

case class Part(manufacturer: String, partNumber: String) 
val part: Part = jvalue.extract[Part] 

,如果你不能在你的案件類更改字段名稱使用相同的字段名稱,你需要它會更容易按照這裏的說明執行自定義串行器Deserialization of case object in Scala with JSON4S

+0

進行了更改並且工作正常。謝謝。 –