【问题标题】:How to read json array in scala using the Play framework如何使用 Play 框架在 scala 中读取 json 数组
【发布时间】:2016-03-31 01:21:19
【问题描述】:

我有以下 Json 作为var dataObject ={"files": ["code.R", "data.cv", "input.txt"]}。 我从客户端将此 json 作为正文发布,我想解析 Json 并在 play scala 中的服务器端读取这些文件名。

请帮忙

【问题讨论】:

    标签: scala playframework-2.0


    【解决方案1】:

    因为你只有一个字段,所以不能使用 json 组合器, 但你可以这样做:

    case class Selection(files:List[String])
    object Selection{
       implicit val selectionReads = (__ \ 'files).read[List[String]].map{ l => Selection(l) }
       implicit val selectionWrites = (__ \ 'files).write[List[String]].contramap { (selection: Selection) => selection.files}
    
       //You can replace the above 2 lines with this line - depends on you.
       implicit val selectionFormat: Format[Selection] = (__ \ 'files).format[List[String]].inmap(files => Selection(files), (selection: Selection) => selection.files)
    }
    

    确保你导入:

    import play.api.libs.functional.syntax._
    

    【讨论】:

    • 如何打印选中的文件名
    • Json.stringify(Json.toJson(Selection(List("x","y","z")))) @sanmoypaul
    • 嘿@Tomer,你的答案的第一个字有一点错误。
    【解决方案2】:

    这是文档:https://www.playframework.com/documentation/2.5.x/ScalaJson

    而且解决方法很简单:

    import play.api.libs.json._
    
    val json: JsValue = Json.parse("{ "files": ["code.R","data.csv","input.txt"] }")
    
    val files = (json \ "files").get
    

    【讨论】:

    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多