从包含Some和None值的列表中使用Json4S生成Json字符串 [英] Generating Json string using Json4S from a list containing Some and None values
问题描述
我正在使用Scalatra,后者又使用Json4S生成Json字符串.我收到
I am using Scalatra, which in turn uses Json4S to generate Json string. I receive
["A","B"]
["A","B"]
对于
List(Some("A"),None,Some("B"))
List(Some("A"),None,Some("B"))
我想收到
["A",未定义,"B"]
["A",undefined,"B"]
如何解决?
推荐答案
undefined
即使在javascript中有效,也不是有效的json值.
来自 rfc4627 (应用程序/json):
undefined
is not a valid json value, even though it is valid in javascript.
From rfc4627 (application/json):
JSON值必须是对象,数组,数字或字符串,或者是以下之一 以下三个文字名称:
A JSON value MUST be an object, array, number, or string, or one of the following three literal names:
false null真
false null true
(未提及未定义)
但是,与null
而不是undefined
相比,这很简单.在scala控制台中,首先导入几个:
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
客户序列化程序:
scala> class NoneJNullSerializer extends CustomSerializer[Option[_]](format => ({ case JNull => None }, { case None => JNull }))
瞧,
scala> implicit val formats = DefaultFormats + new NoneJNullSerializer()
scala> val ser = write(List(Some("A"), None, Some("B")))
ser: String = ["A",null,"B"]
这篇关于从包含Some和None值的列表中使用Json4S生成Json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!