仍然是Scala的菜鸟,我在这里碰壁了。
使用 Scala 2.12.1 和 liftweb 3.0.1
我有像这样的 json 代码
{
"traces":[
[
{
"matcher":"Matcher1",
"score":{
"assigned":50,
"max":50
}
},
{
"matcher":"Matcher2",
"score":{
"assigned":50,
"max":50
}
},
{
"matcher":"Matcher3",
"score":{
"assigned":50,
"max":50
}
}
],
[
{
"matcher":"Matcher4",
"score":{
"assigned":50,
"max":50
}
},
{
"matcher":"Matcher5",
"score":{
"assigned":50,
"max":50
}
},
{
"matcher":"Matcher6",
"score":{
"assigned":50,
"max":50
}
}
]
]
}
我正在尝试将其解析为具有以下行的某些情况
case class Traces (traces: List[List[Trace]])
case class Trace (matcher: String, score: Score)
val result = parse(json).extract[Traces]
我知道我在思考中采取了一些错误的退出,但我似乎找不到一种方法来有效地解析这样的 json。
任何为我指明正确方向的帮助将不胜感激。
[编辑]我开始明白,我在这里确实问错了问题。问题是我的示踪剂列表确实得到了 Nil。经过进一步调查,我发现我确实将嵌套的示踪剂类放在了主类的错误级别。提供的答案和评论确实使我朝着正确的方向前进,因此投了赞成票并接受了。
不知道为什么我得到了反对票,但我想某人的自尊心需要通过放下菜鸟来提升;-(
感谢您的帮助和答案。
我不确定什么对你不起作用。你能提供更多信息吗?
val json =
"""
|{
| "traces":
| [[
| {"matcher": "Matcher1","score": {"assigned": 50,"max": 50}},
| {"matcher": "Matcher2","score": {"assigned": 50,"max": 50}},
| {"matcher": "Matcher3","score": {"assigned": 50,"max": 50}}
| ],
| [
| {"matcher": "Matcher4","score": {"assigned": 50,"max": 50}},
| {"matcher": "Matcher5","score": {"assigned": 50,"max": 50}},
| {"matcher": "Matcher6","score": {"assigned": 50,"max": 50}}
| ]]
| }
""".stripMargin
import net.liftweb.json._
implicit val formats = DefaultFormats
case class Traces (traces: List[List[Trace]])
case class Trace (matcher: String, score: Score)
case class Score(assigned: Int, max: Int)
val result = parse(json).extract[Traces]
上面的代码对我来说效果很好。