问题描述
我有一个 JSON 对象,我已经对其进行了转换,我只需要过滤到其原始键的一个子集。我已经在 circe 中查看了 Json
对象的文档,但它似乎没有公开任何关于过滤对象的 API。我必须为此使用游标吗?我考虑过从 case 类创建解码器,但是我的键中有一个特殊字符 .
。这里有更多用于上下文的代码/数据。
{
"field.nested.this": "value","field.nested.that": "value","field.nested.where": "value"
}
创建不包含 field.nested.that
字段的新 JSON 实例的最佳方法是什么?
解决方法
我不确定这是否是您需要的:
object Circe extends App {
import io.circe._
import io.circe.literal._
import io.circe.syntax._
//I'm using a json literal here.
//If you have a runtime string from an external source
// you would need to parse it with `io.circe.parser.parse` first
val json: Json = json"""
{
"field.nested.this": "value","field.nested.that": "value","field.nested.where": "value"
}
"""
val maybeJsonFiltered =
json.asObject.map(_.filterKeys(_ != "field.nested.that").asJson)
println(maybeJsonFiltered)
// Some({
// "field.nested.this" : "value",// "field.nested.where" : "value"
// })
}
或者,您也可以将其解析为地图 (json.as[Map[String,String]]
) 或仅包含您需要的字段的自定义案例类,并将它们编码回 json。您可能需要使用 @JsonKey
为所有字段添加 .
注释。