【问题标题】:Getting value from JSON and processing depending on variable type - Scala从 JSON 中获取价值并根据变量类型进行处理 - Scala
【发布时间】:2021-11-27 09:24:09
【问题描述】:

我是 Scala 新手,我需要根据两种情况弄清楚如何处理 JSON。

首先是我收到这样一个 JSON 的地方: {..."field":[{"count":1,"value":"foo"}]...}
第二种情况是我收到这种 JSON:{..."field":"foo"...}

我无法确定每个 JSON 何时会进入(它是随机的)。在这两种情况下,我都需要获取 field 值并将其作为字符串存储到单独的 JSON 中。第二种情况很明显,因为它已经是一个字符串,但我不知道如何确定这个字段是数组还是字符串,如果是数组,然后从其中的 JSON 获取"foo"。我知道如何访问field,因为它是一个游标:
val field = cursor.downField("foo").downField("bar").downField("lorem").downField("field")
下面是我的方法不起作用的示例:

if (field.asInstanceOf[String]) {
    rowFiltered.set("field", field.as[String])
} else {
    rowFiltered.set("field", field.as[Seq[field[0]]])
}

我们将不胜感激帮助确定和分配。

【问题讨论】:

  • 看起来应该是 isInstanceOf 而不是 asInstanceOf 但也许这是一个错字。

标签: arrays json scala


【解决方案1】:

您可以使用orElse 并传递另一个解析。

import io.circe._
import io.circe.literal.JsonStringContext


object App {

  final case class MyField(value: String)

  def main(args: Array[String]): Unit = {
    val jsonValue01: Json =
      json"""{
            "hello": "world",
            "field":[{"count":1,"value":"foo01"}],
            "foo" : "bar"
            }"""

    val jsonValue02: Json =
      json"""{
            "hello": "world",
            "field": "foo02",
            "foo" : "bar"
            }"""

    implicit val decodeField: Decoder[MyField] = new Decoder[MyField] {
      final def apply(c: HCursor): Decoder.Result[MyField] =
        for {
          foo <- c.downField("field").downN(0).downField("value").as[String]
                  .orElse(c.downField("field").as[String])
        } yield {
          new MyField(foo)
        }
    }

    val myField01 = jsonValue01.as[MyField]
    val myField02 = jsonValue02.as[MyField]

    println(myField01) //Right(MyField(value = foo01))
    println(myField02) //Right(MyField(value = foo02))

  }
}


【讨论】:

  • 感谢您的意见!我现在面临以下错误:value orErase is not a mamber of io.circe.Decored.Result[String]
  • 我尝试更改输入值,因为我有一个 hcursor 作为输入并尝试执行 val field = data.hcursor.downField('foo').downField('bar').as[io.circe.Json] 但也收到错误
  • 不是orErase,而是orElse
  • 已导入import cats.syntax.either._,运行良好,谢谢,将验证数据是否会正确提取,再次感谢!
猜你喜欢
  • 2018-03-06
  • 2016-02-04
  • 2018-11-08
  • 2015-08-30
  • 2018-10-08
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 2011-01-08
相关资源
最近更新 更多