scala 不同结构的嵌套Map

cig3rfwq  于 2022-11-09  发布在  Scala
关注(0)|答案(1)|浏览(189)

我是Scala的新手,我想构建一个如下所示的对象,然后转换为Json,但这样做会出错。我怎样才能做到这一点呢?
这就是我尝试过的:

Map(a -> Map(b-> "1", c -> "2"),
Map(d -> values.map(v => Map(b-> v.value1, c -> v.value2)))
.asJson

预期结果:

{
"a":{"b": "1", "c": "2"},
"d":[{"b":"x1","c":"x2"},{"b":x3,"c":"x4"}...]
}
rjee0c15

rjee0c151#

您应该保留使用JSON库提供的DSL,即Circe JSON DSL:

import io.circe.Json
import io.circe.syntax.*

Json.obj(
  "a" := Json.obj("b" := "1", "c" := "2")
  "d" := values.map(v => Json.obj("b" := v.value1, "c" := v.value2))
)

相关问题