I'm trying to make a simple example of a class serialization in Scala using json4s library, but even after extensively searching for it on the internet, unfortunately I couldn't find any satisfatory sample that would solve my problem.
Basically I have a simple class called Person and I want to extract an instance of this class from a JSON string.
case class Person(
val name: String,
val age: Int,
val children: Option[List[Person]]
)
So when I do this:
val jsonStr = "{\"name\":\"Socrates\", \"age\": 70}"
println(Serialization.read[Person](jsonStr))
I get this output:
"Person(Socrates,70,None)" // works fine!
But when I have no age parameter in JSON string, I get this error:
Exception in thread "main" org.json4s.package$MappingException: No usable value for age
I know that Person class has two required parameters in its constructor, but I would like to know if there's a way to make this conversion through a parser or something similar.
Also, I've tried to make this parser, but no success.
Thanks in advance for any help.
Option, return a special value, useOptionfor theageparameter, use a specialagenumber to represent "not specified", return aTryorEither... the list goes on and on. Are you asking for help coding a parser, or deciding what your code should do in the first place?