我正在尝试在scala中解析JSON而且我不是很成功。 这是我的JSON结构:
{
"data" : "test",
"field" : "test",
"listObj" : [{
"data" : "testInner1",
"field" : "testInner1"
} , {
"data" : "testInner2",
"field" : "testInner2"
}],
"obj" : {
"data" : "testInner1",
"field" : "testInner1"
}
}
我正用电梯解析。这是我的代码:
import net.liftweb.json._
implicit val formats = DefaultFormats
case class MyJson(data: String, field: String, obj: MyJson, listObj: List[MyJson])
val json = parse("""
{
"data" : "test",
"field" : "test",
"listObj" : [{
"data" : "testInner1",
"field" : "testInner1"
} , {
"data" : "testInner2",
"field" : "testInner2"
}],
"obj" : {
"data" : "testInner1",
"field" : "testInner1"
}
}""")
println(json.extract[Query])
我是上帝以下的例外:
Caused by: net.liftweb.json.MappingException: No usable value for operation
Did not find value which can be converted into java.lang.String
at net.liftweb.json.Meta$.fail(Meta.scala:191)
at net.liftweb.json.Extraction$.mkValue$1(Extraction.scala:357)
at net.liftweb.json.Extraction$.net$liftweb$json$Extraction$$build$1(Extraction.scala:317)
at net.liftweb.json.Extraction$$anonfun$13.apply(Extraction.scala:253)
at net.liftweb.json.Extraction$$anonfun$13.apply(Extraction.scala:253)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
at scala.collection.immutable.List.foreach(List.scala:318)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
at scala.collection.AbstractTraversable.map(Traversable.scala:105)
at net.liftweb.json.Extraction$.instantiate$1(Extraction.scala:253)
at net.liftweb.json.Extraction$.newInstance$1(Extraction.scala:286)
at net.liftweb.json.Extraction$.net$liftweb$json$Extraction$$build$1(Extraction.scala:315)
at net.liftweb.json.Extraction$.mkValue$1(Extraction.scala:351)
... 34 more
Caused by: net.liftweb.json.MappingException: Did not find value which can be converted into java.lang.String
at net.liftweb.json.Meta$.fail(Meta.scala:191)
at net.liftweb.json.Extraction$.convert(Extraction.scala:403)
at net.liftweb.json.Extraction$.net$liftweb$json$Extraction$$build$1(Extraction.scala:314)
at net.liftweb.json.Extraction$.mkValue$1(Extraction.scala:351)
... 46 more
我尝试过使用json4s,但我可以设法解析为case类。当我从我的JSON中删除obj和objList时,它运行良好。
任何人都可以指出我解析这种结构以在Scala中读取它的方法吗?
答案 0 :(得分:3)
更改案例类定义,以便obj
是可选值:
case class MyJson(data: String,
field: String,
// obj: MyJson, // from
obj: Option[MyJson], // to
listObj: List[MyJson])
这是必需的,以便json提取器仍然可以生成MyJson
的{{1}}实例,即使json缺少"obj"
字段(它在示例中的嵌套结构中也是如此)。
listObj
不需要这样做,因为json中缺少"listObj"
字段仍然可以表示为List[MyJson]
的空列表。