我正在努力理解解析嵌套和动态JSON,我已经通过liftweb api对其进行了解析,然后将其映射为键值。然后,我应用了平面映射来破坏所有json以便提取,现在我想了解如何提取所需的值或是否被询问如何更改任何键,以便以后可以读取该值。 我是Scala编程的新手,所以如果有任何基本错误,请多多包涵,让我知道如何更正。谢谢。
到目前为止我所做的是
package myJson
import akka.event.Logging.Debug
import javax.naming.directory.SearchResult
import net.liftweb.json.JsonAST.JValue
import net.liftweb.json.DefaultFormats
import net.liftweb.json._
import org.apache.avro.data.Json
import scala.collection.mutable.ArrayBuffer
object myJsonFile extends App {
implicit val formats: DefaultFormats.type = DefaultFormats
val myJson =
"""
{
"quiz": {
"sport": {
"q1": {
"question": "Which one is correct team name in NBA?","options": [
"New York Bulls","Los Angeles Kings","Golden State Warriros","Huston rocket"
],"answer": "Huston rocket"
}
},"maths": {
"q1": {
"question": "5 + 7 = ?","options": [
"10","11","12","13"
],"answer": "12"
},"q2": {
"question": "12 - 8 = ?","options": [
"1","2","3","4"
],"answer": "4"
}
}
}
}
"""
val json = parse(myJson)
val elements = (json \\ "quiz").children
val elements1 = (json \\ "sport").children
val elements2 = (json \\ "maths").children
val elements3 = (json \\ "q1").children
val elements4 = (json \\ "q2").children
val elements5 = (json \ "quiz" \ "sport" \ "q1" \ "question")
//val elements6 = (json \ "quiz" \ "sport" \\ "q1").children
val elements7 = (json \\"q1") .children
val elements8 = (json \ "quiz" \ "sport" \ "q1" \ "question").extract[String]
val elements9 = (json \ "quiz" \ "sport" \ "q1" \ "options").children
if (elements.isEmpty == true) {
println("No Quiz")
}
if (elements.isEmpty == false) {
println("Quiz Children Exists and continuing")
}
if (elements1.isEmpty == true) {
println("No Sport Children")
}
if (elements1.isEmpty == false) {
println("Sport Children Exists and continuing")
}
if (elements2.isEmpty == true) {
println("No Maths Children")
}
if (elements2.isEmpty == false) {
println("Maths Children Exists and continuing")
}
if (elements3.isEmpty == true) {
println("No q1 Children")
}
if (elements3.isEmpty == false) {
println("q1 Children Exists and continuing")
}
if (elements4.isEmpty == true) {
println("No q2 Children")
}
if (elements4.isEmpty == false) {
println("q2 Children Exists and continuing")
}
else "Function Crashed"
val jsonmap: Map[String,Any] = json.values.asInstanceOf[Map[String,Any]]
println("Mapped JSON : " + jsonmap)
for ((key,value) <- jsonmap) {
println("key = " + key + ",value = " + value.toString)}
println("now flatmapppppp")
val jsonflatmap = jsonmap.flatMap(s=>jsonmap)
println(jsonflatmap)
for(s <- jsonflatmap)
{
println(s._1)
println(s._2)
}
}
case class parseJson(quiz:q_Types)
case class q_Types(sport:sport_q,maths_q:maths_q)
case class sport_q(q1:q1)
case class q1(question:Option[String],options:List[Option[String]],answer:Option[String])
case class maths_q(q1:q1,q2:q2)
case class q2 (question:Option[String],answer:Option[String])
现在我在这里做错了什么,或者如何使我的数据可用?