【问题标题】:Parse Jsvalue using scala使用 scala 解析 Jsvalue
【发布时间】:2016-01-11 21:52:23
【问题描述】:

我是 scala 的新手。我有一个 Json 文件,我将它读入字符串。然后我将字符串解析为 JSValue。现在我正在尝试读取所有值以更新我的数据库,但我不知道如何继续。

val l = scala.io.Source.fromFile("list.json").getLines().mkString
val result: JsValue = Json.parse(l)

我的 Json 是这样的:

{
    picture_id : xxx
    width : xxx
    height : xxx
},
{
    picture_id : xxx
    width : xxx
    height : xxx
},    

....

我想提取偶数块来用正确的值更新数据库。

谢谢。

【问题讨论】:

    标签: json scala parsing


    【解决方案1】:

    您应该执行以下操作。我希望 cmets 是解释性的:

    val l = scala.io.Source.fromFile("list.json").getLines().mkString
    val result: JsValue = Json.parse(l)
    
    //Create a model to hold your json objects
    case class Pic(id: String, width: String, height: String)
    
    //Create a reader that reads your json string to your model(Pic)
    implicit val picReads: Reads[Pic] = (
      (JsPath \ "picture_id").read[String] and
        (JsPath \ "width").read[String] and
        (JsPath \ "height").read[String] and
      )(Pic.apply _)
    
    result.validate[List[Pic]] match {
      case s: JsSuccess[List[Pic]] => 
        //Deal with your list of pics here
      case e: JsError => println("Errors: " + JsError.toFlatJson(e).toString())
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多