Generating Json string using Json4S from a list containing Some and None values

夙愿已清 提交于 2019-12-19 09:43:39

问题


I am using Scalatra, which in turn uses Json4S to generate Json string. I receive

["A","B"]

for

List(Some("A"),None,Some("B"))

I would like to receive

["A",undefined,"B"]

How can this be fixed ?


回答1:


undefined is not a valid json value, even though it is valid in javascript. From rfc4627 (application/json):

A JSON value MUST be an object, array, number, or string, or one of the following three literal names:

false null true

(no mention of undefined)

However this is fairly straight-forward to do with null instead of undefined. In the scala console, first a couple imports:

scala> import org.json4s._
scala> import org.json4s.native.Serialization.write

A customer serializer:

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

And voila:

scala> implicit val formats = DefaultFormats + new NoneJNullSerializer()
scala> val ser = write(List(Some("A"), None, Some("B")))
ser: String = ["A",null,"B"]


来源:https://stackoverflow.com/questions/16872893/generating-json-string-using-json4s-from-a-list-containing-some-and-none-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!