LoginSignup
2
1

More than 5 years have passed since last update.

json4s, play-jsonでのOption#emptyの取扱い

Last updated at Posted at 2017-05-31

json4s

valueがJNullの場合はnullをvalueとする、JNothingの場合はfieldごと除去

scala> compact(render(("aaa" -> 123) ~ ("bbb" -> JNull)))
res: String = {"aaa":123,"bbb":null}
scala> compact(render(("aaa" -> 123) ~ ("bbb" -> JNothing)))

Optionで値が存在しない場合はJNothingが選ばれ、fieldごと除去される

res: String = {"aaa":123}
scala> ("aaa" -> 123) ~ ("bbb" -> Option.empty[Int])
res: org.json4s.JsonAST.JObject = JObject(List((aaa,JInt(123)), (bbb,JNothing)))
scala> ("aaa" -> 123) ~ ("bbb" -> Option.empty[String])
res: org.json4s.JsonAST.JObject = JObject(List((aaa,JInt(123)), (bbb,JNothing)))

備考

NullがAnyRefの親クラスであるため、String等AnyRefの系列のときのみnullが使える

scala> ("aaa" -> 123) ~ ("bbb" -> Option.empty[String].orNull)
res: org.json4s.JsonAST.JObject = JObject(List((aaa,JInt(123)), (bbb,JString(null))))
scala> ("aaa" -> 123) ~ ("bbb" -> Some(1).orNull)
<console>:23: error: Cannot prove that Null <:< Int.
 ("aaa" -> 123) ~ ("bbb" -> Some(1).orNull)
 ^

play-json

基本的にfieldごと除去するようなことはしない。

scala> Json.obj("aaa" -> 123, "bbb" -> JsNull)
res: play.api.libs.json.JsObject = {"aaa":123,"bbb":null}
scala> Json.obj("aaa" -> 123, "bbb" -> JsNull).toString()
res: String = {"aaa":123,"bbb":null}
scala> Json.stringify(Json.obj("aaa" -> 123, "bbb" -> JsNull))
res: String = {"aaa":123,"bbb":null}
scala> Json.stringify(Json.obj("aaa" -> 123, "bbb" -> Option.empty[Int]))
res: String = {"aaa":123,"bbb":null}
scala> Json.stringify(Json.obj("aaa" -> 123, "bbb" -> Option.empty[String]))
res: String = {"aaa":123,"bbb":null}

play.api.libs.json.JsPath#writeNullableを用いて記述されている場合はfieldごと除去

scala> (((__ \ 'aaa).write[Int] ~ (__ \ 'bbb).writeNullable[String])(identity[(Int, Option[String])] _)).writes((123, None))
res: play.api.libs.json.JsObject = {"aaa":123}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1