3

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 ?

Ali Salehi
  • 6,899
  • 11
  • 49
  • 75
  • Why do you want that undefined in there? How could the receiver of that information possible benefit from having an undefined in there vs just not having that element in the array? – cmbaxter Jun 01 '13 at 13:34
  • 1
    When I serialise an array with 3 elements, I am expecting to receive a new array with 3 elements. Moreover: List(Some("A"),None,Some("B")) <> List(Some("A"),Some("B"),None) while the serialised arrays are equivalent !!! I reckon this is a bug in Json4S library. – Ali Salehi Jun 02 '13 at 02:34

1 Answers1

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"]
theon
  • 14,170
  • 5
  • 51
  • 74
  • This does not seem to solve the problem when the None is a value in a Map. The entire key seems to be stripped before the implicit conversion is hit. – Nick Mitchinson Jan 18 '14 at 00:30
  • [edited] Whoops, forgot this was json4s and wrote a comment about spray-json :s – theon Jan 18 '14 at 21:42
  • This issue is solved in 3.2.11 version, you coud just use DefaultFormats.preservingEmptyValues. If anyone has issue, refer this http://stackoverflow.com/questions/27855934/json4s-ignoring-the-none-feilds-while-seriallization – S.Karthik Jan 09 '15 at 10:48