gpt4 book ai didi

scala - json4s 删除值为 None 的键

转载 作者:行者123 更新时间:2023-12-03 18:57:55 25 4
gpt4 key购买 nike

我一直致力于使用 the docs 中描述的隐式转换从 Scalatra 应用程序返回 JSON .

我注意到从生成的 JSON 中删除了带有空选项(即 None)的键(而不是 null,这似乎是预期的行为)

我试图使用隐式转换将 None 转换为 null,例如:

class NoneJNullSerializer extends CustomSerializer[Option[_]](format => (
{
case JNull => None
}, {
case None => JNull
}
))

protected implicit val jsonFormats: Formats = DefaultFormats.withBigDecimal + new NoneJNullSerializer()

然而,这些键似乎在执行自定义序列化程序之前就被剥离了。

有没有人找到解决办法?

请注意 this question 中描述的解决方案适用于所描述的数组情况,但似乎不适用于 map 。

更新:这是我一直在使用的测试:

  get("/testJSON") {
Map(
"test_key" -> "testValue" ,

"test_key6" -> "testValue6" ,
"subObject" -> Map(
"testNested1" -> "1" ,
"testNested2" -> 2 ,
"testArray" -> Seq(1, 2, 3, 4)
),
"testNone" -> None ,
"testNull" -> null ,
"testSomeNull" -> Some(null) ,
"testJNull" -> JNull ,
"testSomeJNull" -> Some(JNull)
)
}

我正在寻找的输出是

{
"test_key": "testValue",
"test_some_j_null": null,
"sub_object": {
"test_nested1": "1",
"test_nested2": 2,
"test_array": [
1,
2,
3,
4
]
},
"test_none": null,
"test_j_null": null,
"test_key6": "testValue6",
"test_null": null,
"test_some_null": null
}

我也在用


protected override def transformResponseBody(body: JValue): JValue = { body.underscoreKeys }

对于带下划线的键

最佳答案

使用自定义序列化器应该也适用于 map 。

import org.json4s._
import org.json4s.jackson.JsonMethods._

object testNull extends App {

val data = Map(
"testNone" -> None,
"testNull" -> null,
"testSomeNull" -> Some(null),
"testJNull" -> JNull,
"testSomeJNull" -> Some(JNull)
)

class NoneJNullSerializer extends CustomSerializer[Option[_]](format => ( {
case JNull => None
}, {
case None => JNull
}))

implicit val formats = DefaultFormats + new NoneJNullSerializer

val ast = Extraction.decompose(data)

println(pretty(ast))

// {
// "testSomeJNull" : null,
// "testJNull" : null,
// "testNone" : null,
// "testNull" : null,
// "testSomeNull" : null
// }

}

关于scala - json4s 删除值为 None 的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21199250/

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