Ian
Ian

Reputation: 6144

Parse empty string as None with Json4s

I know Json4s handles Options on its own and most of the time this works great - for Option[T] it serializes None to missing value and reads missing value as None while automatically using the correct serializer/deserializer for T otherwise.

My problem is that I have a database where empty strings have been used as missing values, so I want to read those as None. A simple example:

case class Example(a: Option[Number])
val inputJson = """ {"a": ""} """
Serialization.read[Example](inputJson) // I want Example(None)

I thought I could do this pretty easily with a custom serializer, for example:

case object EmptyValueSerializer extends CustomSerializer[Option[_]](_ => (
  {case JString("") => None},
  {PartialFunction.empty}
))

This does work to read empty strings as None, however if the JSON value is not an empty string, it errors (ie, for the previous example, it would throw an error on {"a": "5"}). How can I get Json4s to continue parsing the value using it's default behavior if it's not an empty string?

Theoretically I thought about using a typetag T and adding a default case like case v => Serialization.write[T](v), but I'm not sure if that's the best way and I also can't really wrap my head around what that would look like in code.

Upvotes: 0

Views: 465

Answers (1)

gaf
gaf

Reputation: 201

A bit late to the pass but you just need another case statement

case object EmptyValueSerializer extends CustomSerializer[Option[_]](_ => (
  {
    case JString("") => None
    case JString(s) => Option(s)
  },
  {PartialFunction.empty}
))

Upvotes: 0

Related Questions