pog*_*ogo 7 scala spray spray-json
我正在尝试(并且失败)了解spray-json如何将json提要转换为对象.如果我有一个简单的键 - >值json feed然后它似乎工作正常但我想要读取的数据出现在这样的列表中:
[{
"name": "John",
"age": "30"
},
{
"name": "Tom",
"age": "25"
}]
Run Code Online (Sandbox Code Playgroud)
我的代码看起来像这样:
package jsontest
import spray.json._
import DefaultJsonProtocol._
object JsonFun {
case class Person(name: String, age: String)
case class FriendList(items: List[Person])
object FriendsProtocol extends DefaultJsonProtocol {
implicit val personFormat = jsonFormat2(Person)
implicit val friendListFormat = jsonFormat1(FriendList)
}
def main(args: Array[String]): Unit = {
import FriendsProtocol._
val input = scala.io.Source.fromFile("test.json")("UTF-8").mkString.parseJson
val friendList = input.convertTo[FriendList]
println(friendList)
}
}
Run Code Online (Sandbox Code Playgroud)
如果我更改我的测试文件,所以它只有一个人不在数组中运行val friendList = input.convertTo[Person]然后它工作,一切都解析但是一旦我尝试解析一个数组它失败并出现错误Object expected in field 'items'
任何人都可以指出我做错的方向吗?
嗯,通常是在花了几个小时试图让某些东西工作之后立即向StackOverflow发布内容后的方式,我已经设法让这个工作.
FriendsProtocol的正确实现是:
object FriendsProtocol extends DefaultJsonProtocol {
implicit val personFormat = jsonFormat2(Person)
implicit object friendListJsonFormat extends RootJsonFormat[FriendList] {
def read(value: JsValue) = FriendList(value.convertTo[List[Person]])
def write(f: FriendList) = ???
}
}
Run Code Online (Sandbox Code Playgroud)
告诉Spray如何读/写(只是在我的情况下读)列表对象足以让它工作.
希望能帮助别人!
| 归档时间: |
|
| 查看次数: |
7836 次 |
| 最近记录: |