docsで説明されている暗黙的な変換を使用して、Scalatra アプリケーションから JSON を返すように取り組んできました。
空のオプション (つまり、None) を持つキーが結果の JSON から取り除かれていることに気付きました (予想される動作のように見える null ではなく)。
None
次のように、暗黙的な変換を使用して にキャストしようとしましたnull
。
class NoneJNullSerializer extends CustomSerializer[Option[_]](format => (
{
case JNull => None
}, {
case None => JNull
}
))
protected implicit val jsonFormats: Formats = DefaultFormats.withBigDecimal + new NoneJNullSerializer()
ただし、カスタムシリアライザーの実行前にキーが取り除かれているようです。
誰かがこれに対する解決策を見つけましたか?
この質問で説明されているソリューションは、説明されている配列のケースでは機能しますが、マップでは機能しないようです。
更新: これは私が使用しているテストです:
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 }
下線付きキーの場合