I'm using liftweb to parse JSON from String in scala, some of record have 3 field
val a = {"name": "Alice", "age": 21, "job": "nurse"}
but some other have only 2 field
val b = {"name": "Bob", "age": 30}
I created case class Person(name: String, age: Long, job: String) and when I call parse(a) it return value successfully, but when I call parse(b) it appear exception
net.liftweb.json.MappingException: No usable value for algorithm
Did not find value which can be converted into java.lang.String
If you make the parameter type job:String
you are going to have issues since that would require the parameter to have a value - and in your example it doesn't.
I'll assume we want to make that an Option[String]
and in the example below just add multiple constructors to match your parameters. Something like this should work:
case class Person(name: String, age: Long, job: Option[String]){
def this(name: String, age: Long) = this(name, age, None)
}
If you had a default value, and wanted job
to be a String
just change the None
to whatever you want by default.
After that, parsing as you did above should work for both cases.