abr*_*nan 8 json scala spray-json
我是Spray-Json API的新手,我正在尝试解析Docker REST API中的Json响应.
有一个使用Spray-Json解析此Google Map Json响应的简洁示例:
{
"results" : [
{
"elevation" : 8815.7158203125,
"location" : {
"lat" : 27.988056,
"lng" : 86.92527800000001
},
"resolution" : 152.7032318115234
}
],
"status" : "OK"
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,最外层是一个Object.但是,我需要直接解析一个Json响应,其最外层是Array由容器信息组成,如下所示:
[
{
"Id": "8dfafdbc3a40",
"Image": "base:latest",
"Command": "echo 1",
"Created": 1367854155,
"Status": "Exit 0",
"Ports":[{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}],
"SizeRw":12288,
"SizeRootFs":0
},
{ ... },
{ ... }
]
Run Code Online (Sandbox Code Playgroud)
以下是我根据Google地图示例改编的代码:
package main
import ...
case class Container(id: String, image: String, command: String, created: Long, status: String, ports: List[Port], sizeRW: Long, sizeRootFs: Long)
case class Port(privatePort: Long, publicPort: Long, portType: String)
case class DockerApiResult[T](results: List[T])
object ContainerListJsonProtocol extends DefaultJsonProtocol {
implicit val portFormat = jsonFormat3(Port)
implicit val containerFormat = jsonFormat8(Container)
implicit def dockerApiResultFormat[T :JsonFormat] = jsonFormat1(DockerApiResult.apply[T])
}
object Main extends App {
implicit val system = ActorSystem("simple-spray-client")
import system.dispatcher // execution context for futures below
val log = Logging(system, getClass)
log.info("Requesting containers info...")
import ContainerListJsonProtocol._
import SprayJsonSupport._
val pipeline = sendReceive ~> unmarshal[DockerApiResult[Container]]
val responseFuture = pipeline {
Get("http://<ip-address>:4243/containers/json")
}
responseFuture onComplete {
case Success(DockerApiResult(Container(_,_,_,_,_,_,_,_) :: _)) =>
log.info("Id of the found image: {} ")
shutdown()
case Success(somethingUnexpected) =>
log.warning("The Docker API call was successful but returned something unexpected: '{}'.", somethingUnexpected)
shutdown()
case Failure(error) =>
log.error(error, "Couldn't get containers information")
shutdown()
}
def shutdown(): Unit = {
IO(Http).ask(Http.CloseAll)(1.second).await
system.shutdown()
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我得到的例外(Object expected):
spray.httpx.PipelineException: MalformedContent(Object expected,Some(spray.json.DeserializationException: Object expected))
Run Code Online (Sandbox Code Playgroud)
我当然错过了一些显而易见但如何使用Spray-Json解析Json数组?
此外,有没有一个简单的方法来做到这一点,而无需处理自定义JsonFormat或RootJsonFormat?
kon*_*ong 14
通过这样做unmarshal[DockerApiResult[Container]],你告诉spray-json你希望格式是表单的json对象:
{ results: [...] }
Run Code Online (Sandbox Code Playgroud)
since case class DockerApiResult[T](results: List[T])被定义为具有包含列表的单个结果字段的对象.
相反,你需要做:
unmarshal[List[Container]]
Run Code Online (Sandbox Code Playgroud)
然后直接对结果列表进行操作(或者在使用spray-json解析之后将其包装在DockerApiResult中).
如果你想让spray-json直接解组到DockerApiResult中,你可以用以下代码编写一个JsonFormat:
implicit object DockerApiResultFormat extends RootJsonFormat[DockerApiResult] {
def read(value: JsValue) = DockerApiResult(value.convertTo[List[Container]])
def write(obj: DockerApiResult) = obj.results.toJson
}
Run Code Online (Sandbox Code Playgroud)
与此争斗一点,并找到了一种方法,使用喷雾从json解析的字符串转换为JsArray:
import spray.json._ //parseJson
val kkkk =
"""
|[{"a": "1"}, {"b": "2"}]
""".stripMargin.parseJson.asInstanceOf[JsArray]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16432 次 |
| 最近记录: |