简体   繁体   English

如何在 Scala 中将 JsValue 转换为 Array[Int]?

[英]How can I convert JsValue to Array[Int] in Scala?

I am using the Play Json Library to parse json in scala and I have a value that looks like this我正在使用 Play Json 库来解析 scala 中的 json,我有一个看起来像这样的值

scala> val extract = (payload \ "id")
extract: play.api.libs.json.JsValue = [8,18]

I want to convert JsValue to Array[Int].我想将 JsValue 转换为 Array[Int]。

Well, because, you are working with parsing json - which implies that along with that you need to validate it and properly handle errors, it not so easy just convert it - Play JSON will force you to handle errors.好吧,因为您正在解析 json - 这意味着您需要验证它并正确处理错误,只是转换它并不容易 - Play JSON 将迫使您处理错误。 So, answering your question there you can try something like described below:因此,在那里回答您的问题,您可以尝试如下所述的操作:

   val jsonString = "{\"id\": [1, 2, 3] }"
    val payload = Json.parse(jsonString)
    // This will return `JsResult` - success or failure, which need to be properly handled
    println((payload \ "id").validate[Array[Int]].map(_.toList))

    // This is unsafe operation and might throw exception for un-expected JSON
    println((payload \ "id").validate[Array[Int]].get.toList)

which prints out for me next:接下来为我打印出来:

JsSuccess(List(1, 2, 3),)
List(1, 2, 3)

I added toList just for output readability.我添加toList只是为了输出可读性。 Hope this will help you!希望能帮到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM