Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 743
Ali Salehi Avatar asked Feb 27 '26 03:02

Ali Salehi


1 Answers

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"]
like image 190
theon Avatar answered Mar 01 '26 19:03

theon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!