读取 json 键值但忽略对象

Read json key value but ignore object

我有以下json

"atrr": {
     "data": {
          "id": "asfasfsaf",
          "name": "cal",
          "type": "state"
          "ref": [
            "xyz",
            "uhz",
            "arz"
          ]
        }
}

我正在阅读下面的内容,但没有得到值 k,v

def getData: Map[String, String] = (atrr \ "data").asOpt[Map[String, String]].getOrElse(Map[String, String]())

没有ref它可以工作fine.how我是否在作为对象

的代码中忽略来自json的ref[]

您可以使用自定义 Reads[Map[String, String]],传递给 .as.asOpt 方法。我的方法是使用 Reads.optionNoError[String] 来处理主 atrr 对象中的值,这样任何会导致错误的非字符串字段都将被视为 None.

// explicitly construct something that'd normally be constructed implicitly
val customReads: Reads[Map[String, Option[String]] = 
  Reads.map(Reads.optionNoError[String])

// pass the custom reads explicitly with parens,
// instead of passing the expect type in square brackets
(atrr \ "data").asOpt(customReads)

这导致

Some(
  Map(
    id -> Some(asfasfsaf), 
    name -> Some(cal), 
    type -> Some(state), 
    ref -> None
  )
)

你可以改变你认为合适的方式,例如通过做

.map(_.collect { case (k, Some(v)) => k -> v })