deamon
deamon

Reputation: 92449

How to use default values with Spray Json?

I'm using Spray Json and want to use the default values defined in case classes, if a value is missing in the Json that populates the objects.

Example

Let's say I want to create an object from the case class Person but using a json document without age to do so:

case class Person(name: String, city: String, age: Int = -1)

{"name": "john", "city": "Somecity"}

How can I use the default value with Spray Json?

Upvotes: 2

Views: 1649

Answers (1)

Luís Guilherme
Luís Guilherme

Reputation: 2709

The only way I know how to do this is to use Option[T] as field type. And, if the field is optional, this is the semantically right way to do it:

case class Person(name: String, city: String, age: Option[Int])

When age is not present, age will be None. Since from your example, you use a absurd value (-1) as a marker that age is absent, using an Option will help you much more.

But, if you really need to have a default value, you can either have another case class that is filled from the one you've got from the JSON, using getOrElse, or use getOrElse(defaultValue) in your code when you need it.

Upvotes: 4

Related Questions