Parse json using liftweb in scala with no usable value

女生的网名这么多〃 提交于 2019-12-10 23:58:48

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/34170046/parse-json-using-liftweb-in-scala-with-no-usable-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!