You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala中如何用spray.json解析JSON中的空数组[]?

解决Scala中spray.json解析空数组并转换为指定格式的问题

嘿,我来帮你搞定这个spray.json解析时的空数组处理问题!首先咱们得先把基础的case class和JSON格式定义好,这是spray.json解析的前提,然后再处理你要的转换逻辑。

第一步:定义对应JSON结构的Case Class和JSON协议

首先得把你的JSON结构映射成Scala的case class,这样spray.json才能正确解析:

import spray.json._

// 对应JSON里的单个规则对象
case class MyRule(labelField: String, nodeAttr: Seq[String])
// 对应外层的包裹对象
case class RuleWrapper(my_rule: List[MyRule])

// 定义spray.json的序列化/反序列化协议
object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val myRuleFormat: RootJsonFormat[MyRule] = jsonFormat2(MyRule)
  implicit val ruleWrapperFormat: RootJsonFormat[RuleWrapper] = jsonFormat1(RuleWrapper)
}

第二步:处理空数组的转换逻辑

你需要把nodeAttr转换成两种结果:空数组对应"",非空数组对应逗号分隔的字符串。这里Scala的mkString方法简直是为这个场景量身定做的——当集合为空时,它默认返回空字符串,非空时就用指定分隔符拼接元素,完全不用写额外的判断逻辑!

修改你的转换代码如下:

import MyJsonProtocol._

// 假设你的JSON字符串是这个
val jsonStr = """{ "my_rule":[ { "labelField": "abc", "nodeAttr":[] }, { "labelField": "def", "nodeAttr":["name","surname"] } ] }"""
// 解析成RuleWrapper实例
val parsedJson = jsonStr.parseJson.convertTo[RuleWrapper]

// 转换你需要的Map结构
val my_map = parsedJson.my_rule.map(rule => 
  Map(
    "label" -> rule.labelField,
    "attr" -> rule.nodeAttr.mkString(",")  // 关键就在这里!
  )
)

为什么这个方案好用?

  • 不用写冗余的if-else判断空数组的情况,mkString自动处理两种场景:空数组返回"",非空数组用逗号拼接。
  • 完全符合Scala的函数式编程风格,代码简洁易读。

看看最终结果

运行这段代码后,my_map的结果会是:

List(
  Map("label" -> "abc", "attr" -> ""),
  Map("label" -> "def", "attr" -> "name,surname")
)

完全和你期望的一致!

内容的提问来源于stack exchange,提问作者ScalaBoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:33:14