gpt4 book ai didi

json - Scala argonaut 将 jEmtpyObject 编码为 'false' 而不是 'null'

转载 作者:行者123 更新时间:2023-12-01 12:37:17 24 4
gpt4 key购买 nike

我正在处理一些超出我直接控制范围的代码,我需要对一个选项 [Thing] 进行编码,如果 Thing 存在,则情况与正常情况一样,但是 None 情况必须返回“false”而不是 null。这能轻易完成吗?我正在查看文档,但没有取得太大的成功。

我的代码是这样的:

   case class Thing(name: String)
case class BiggerThing(stuff: String, thing: Option[Thing])

implict val ThingEncodeJson: EncodeJson[Thing] =
EncodeJson(t => ("name" := t.name ) ->: jEmptyObject)

和 BiggerThing 的等价物,json 需要看起来像:

  1. 对于一些人:

    "thing":{"name": "bob"} 
  2. 对于无:

    "thing": false

但目前 None 情况给出:

"thing":null

如何让它返回 false?有人能给我指出正确的方向吗?

干杯

最佳答案

您只需要为 Option[Thing] 定制一个 CodecJson 实例:

object Example {
import argonaut._, Argonaut._

case class Thing(name: String)
case class BiggerThing(stuff: String, thing: Option[Thing])

implicit val encodeThingOption: CodecJson[Option[Thing]] =
CodecJson(
(thing: Option[Thing]) => thing.map(_.asJson).getOrElse(jFalse),
json =>
// Adopt the easy approach when parsing, that is, if there's no
// `name` property, assume it was `false` and map it to a `None`.
json.get[Thing]("name").map(Some(_)) ||| DecodeResult.ok(None)
)

implicit val encodeThing: CodecJson[Thing] =
casecodec1(Thing.apply, Thing.unapply)("name")

implicit val encodeBiggerThing: CodecJson[BiggerThing] =
casecodec2(BiggerThing.apply, BiggerThing.unapply)("stuff", "thing")

def main(args: Array[String]): Unit = {
val a = BiggerThing("stuff", Some(Thing("name")))
println(a.asJson.nospaces) // {"stuff":"stuff","thing":{"name":"name"}}
val b = BiggerThing("stuff", None)
println(b.asJson.nospaces) // {"stuff":"stuff","thing":false}
}
}

thingNone 时,如何在没有 thing 属性的情况下对 BiggerThing 进行编码。然后你需要一个自定义的 EncodeJson[BiggerThing] 实例:

implicit val decodeBiggerThing: DecodeJson[BiggerThing] =
jdecode2L(BiggerThing.apply)("stuff", "thing")

implicit val encodeBiggerThing: EncodeJson[BiggerThing] =
EncodeJson { biggerThing =>
val thing = biggerThing.thing.map(t => Json("thing" := t))
("stuff" := biggerThing.stuff) ->: thing.getOrElse(jEmptyObject)
}

关于json - Scala argonaut 将 jEmtpyObject 编码为 'false' 而不是 'null',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28574518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com