【问题标题】:How to iterate through json array in Scala and apply API call for each json element如何遍历 Scala 中的 json 数组并为每个 json 元素应用 API 调用
【发布时间】:2021-03-15 17:45:25
【问题描述】:
[
  {
    "color": "#759c69",
    "studyId": "4455",
    "value": "Asparagus"
  },
  {
    "color": "#e68cb9",
    "studyId": "4455",
    "value": "Awesome"
  },
  {
    "color": "#6e665d",
    "studyId": "4455",
    "value": "Bear Hug"
  },
  {
    "color": "#5d7ed6",
    "studyId": "4455",
    "value": "Blue Eyes"
  }
]

我想遍历 Scala 中的 JSON 数组并为每个 JSON 元素应用 API 调用。如何在 Scala 中做到这一点?

【问题讨论】:

  • 选择一个Json(有很多选择。例如circeplay-json、upickle、jsonitter-scala 等)。搜索如何将decode String 放入该库中的 List[CaseClasse]。致电 foreach 或该 List 上的任何内容。
  • 或者,选择一个支持 JSON 光学的 JSON 库并运行 fold,这将为每个元素执行副作用。取决于您是否需要了解每个元素出现的上下文。

标签: arrays json scala api


【解决方案1】:

试试这个:

import io.circe.generic.auto._
import io.circe.parser._


object Demo1 extends App {

  case class Param(color: String, studyId: String, value: String)

  val str =
    """[
      |   {
      |      "color":"#759c69",
      |      "studyId":"4455",
      |      "value":"Asparagus"
      |   },
      |   {
      |      "color":"#e68cb9",
      |      "studyId":"4455",
      |      "value":"Awesome"
      |   },
      |   {
      |      "color":"#6e665d",
      |      "studyId":"4455",
      |      "value":"Bear Hug"
      |   },
      |   {
      |      "color":"#5d7ed6",
      |      "studyId":"4455",
      |      "value":"Blue Eyes"
      |   }
      |]""".stripMargin

  val obj = decode[List[Param]](str)

  println(obj.getOrElse(Param("", "", "")))
}

【讨论】:

    【解决方案2】:

    有很多 json 库。例如,您可以查看Scala json parsers performance,以了解使用情况和性能。我将演示如何使用play-json 来完成。我们需要首先创建一个代表您的数据模型的案例类:

    case class Entity(color: String, studyId: String, value: String)
    

    现在我们需要在companion object上创建一个格式化程序:

    object Entity {
      implicit val format: OFormat[Entity] = Json.format[Entity]
    }
    

    假设问题中的json字符串位于jsonString,我们可以从中创建一个JsValue

    val entitiesResult = Json.parse(jsonString)
    

    并将其转换为模型:

    entitiesResult.validate[Seq[Entity]] match {
      case JsSuccess(entities, _) =>
        entities.foreach(println) // Do here the API call you want
      case JsError(errors) =>
        println(errors) // handle json errors here
    }
    

    可以在Scastie 找到完整的运行示例。只是不要忘记将 play-json 添加为依赖项,将以下内容添加到您的 build.sbt

    resolvers += "play-json" at "https://mvnrepository.com/artifact/com.typesafe.play/play-json"
    libraryDependencies += "com.typesafe.play" %% "play-json" % "2.9.1"
    

    【讨论】:

      猜你喜欢
      • 2021-04-02
      • 2016-12-23
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      相关资源
      最近更新 更多