我有一个包含数组数组的JSON。像这样:
{
"id": "532242",
"text": "Some text here. And Here",
"analysis": {
"exec": "true",
"rowID": "always",
"sentences": {
"next": null,
"data": [{
"sequence": "1",
"readability_score_lexical": null,
"readability_score_syntax": null,
"tokens": [{
"word": "Some",
"lemma": "Some"
},
{
"word": "text",
"lemma": "text"
}
]
},
{
"sequence": "3",
"readability_score_lexical": null,
"readability_score_syntax": null,
"tokens": [{
"word": "and",
"lemma": "And"
},
{
"word": "here",
"lemma": "here"
}
]
}
]
}
}
}
结构非常复杂,但我不能在这方面做任何事情,因为是来自API的响应。
我需要的是获取列表"tokens"
对象。
我用lift-web-json做了这个:
case class Token(word:String, lemma:String)
implicit val formats: Formats = net.liftweb.json.DefaultFormats
val jsonObj = net.liftweb.json.parse(json)
val tokens = (jsonObj \\ "tokens").children
for (el <- tokens) {
val m = el.extract[Token]
println(s"Word ${m.word} and ${m.lemma}")
}
但它说:
net.liftweb.json.MappingException: No usable value for word
Do not know how to convert JArray(List(JField(word,JString(Some)), JField(word,JString(text))))
[...]
Caused by: net.liftweb.json.MappingException: Do not know how to convert JArray(List(JField(word,JString(Some)), JField(word,JString(text)))) into class java.lang.String
而且我不明白我怎么能做对。
答案 0 :(得分:0)
你应该通过替换获得你期望的东西:
val tokens = (jsonObj \\ "tokens").children
for (el <- tokens) {
val m = el.extract[Token]
println(s"Word ${m.word} and ${m.lemma}")
}
使用:
val tokens = for {
// tokenList are:
// JArray(List(JObject(List(JField(word,JString(Some)), JField(lemma,JString(Some)))), JObject(List(JField(word,JString(text)), JField(lemma,JString(text))))))
// JArray(List(JObject(List(JField(word,JString(and)), JField(lemma,JString(And)))), JObject(List(JField(word,JString(here)), JField(lemma,JString(here))))))
tokenList <- (jsonObj \\ "tokens").children
// subTokenList are:
// List(JObject(List(JField(word,JString(Some)), JField(lemma,JString(Some)))), JObject(List(JField(word,JString(text)), JField(lemma,JString(text)))))
// List(JObject(List(JField(word,JString(and)), JField(lemma,JString(And)))), JObject(List(JField(word,JString(here)), JField(lemma,JString(here)))))
JArray(subTokenList) <- tokenList
// liftToken are:
// JObject(List(JField(word,JString(Some)), JField(lemma,JString(Some))))
// JObject(List(JField(word,JString(text)), JField(lemma,JString(text))))
// JObject(List(JField(word,JString(and)), JField(lemma,JString(And))))
// JObject(List(JField(word,JString(here)), JField(lemma,JString(here))))
liftToken <- subTokenList
// token are:
// Token(Some,Some)
// Token(text,text)
// Token(and,And)
// Token(here,here)
token = liftToken.extract[Token]
} yield token