我希望在我的案例类和JSON中拥有不同的字段名称,因此我需要一种方便的重命名方式,在编码和解码中都能使用。
有人有好的解决方案吗?
io.circe.generic.extras._
中的JsonKey
注解。以下是文档中的示例:import io.circe.generic.extras._, io.circe.syntax._
implicit val config: Configuration = Configuration.default
@ConfiguredJsonCodec case class Bar(@JsonKey("my-int") i: Int, s: String)
Bar(13, "Qux").asJson
// res5: io.circe.Json = JObject(object[my-int -> 13,s -> "Qux"])
circe-generic-extras
包。implicit val decodeFieldType: Decoder[FieldType] =
Decoder.forProduct5("nth", "isVLEncoded", "isSerialized", "isSigningField", "type")
(FieldType.apply)
如果你有很多不同的字段名称,这是一种简单的方法。 https://circe.github.io/circe/codecs/custom-codecs.html
以下是解码器的代码示例(有些冗长,因为它不会删除旧字段):
val pimpedDecoder = deriveDecoder[PimpClass].prepare {
_.withFocus {
_.mapObject { x =>
val value = x("old-field")
value.map(x.add("new-field", _)).getOrElse(x)
}
}
}
import io.circe._
object CirceUtil {
def renameField(json: Json, fieldToRename: String, newName: String): Json =
(for {
value <- json.hcursor.downField(fieldToRename).focus
newJson <- json.mapObject(_.add(newName, value)).hcursor.downField(fieldToRename).delete.top
} yield newJson).getOrElse(json)
}
编码器
中使用它,如下所示:implicit val circeEncoder: Encoder[YourCaseClass] = deriveEncoder[YourCaseClass].mapJson(
CirceUtil.renameField(_, "old_field_name", "new_field_name")
)
单元测试
import io.circe.parser._
import org.specs2.mutable.Specification
class CirceUtilSpec extends Specification {
"CirceUtil" should {
"renameField" should {
"correctly rename field" in {
val json = parse("""{ "oldFieldName": 1 }""").toOption.get
val resultJson = CirceUtil.renameField(json, "oldFieldName", "newFieldName")
resultJson.hcursor.downField("oldFieldName").focus must beNone
resultJson.hcursor.downField("newFieldName").focus must beSome
}
"return unchanged json if field is not found" in {
val json = parse("""{ "oldFieldName": 1 }""").toOption.get
val resultJson = CirceUtil.renameField(json, "nonExistentField", "newFieldName")
resultJson must be equalTo json
}
}
}
}
implicit
值。但是,您可以在底部添加类似以下内容的代码:implicit val config: Configuration = Configuration.default }```
- Bishwajit Purkaystha