我正在尝试使用groovy脚本将以下JSON文件转换为XML文件
{
"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"
}
}
}
}
但在执行代码后出现此错误错误部分
Caught: groovy.lang.MissingPropertyException: No such property: question for class: java.lang.String
groovy.lang.MissingPropertyException: No such property: question for class: java.lang.String
at json_xml$_run_closure1$_closure2$_closure3$_closure5.doCall(json.xml.groovy:13)
at json_xml$_run_closure1$_closure2$_closure3.doCall(json.xml.groovy:12)
at json_xml$_run_closure1$_closure2$_closure3.doCall(json.xml.groovy)
at json_xml$_run_closure1$_closure2.doCall(json.xml.groovy:12)
at json_xml$_run_closure1$_closure2.doCall(json.xml.groovy)
at json_xml$_run_closure1.doCall(json.xml.groovy:11)
at json_xml$_run_closure1.doCall(json.xml.groovy)
at json_xml.run(json.xml.groovy:10)
有人能告诉我我哪里出错了吗?这将是非常有帮助的,因为我即将到来的项目主要是使用Groovy开发这种类型的转换脚本。我是编码领域的新手。
我写的剧本是这样的。
import groovy.json.JsonSlurper
import groovy.xml.MarkupBuilder
import java.io.*
java.io.StringWriter
def f1 = new File("C:/Users/lenovo/Desktop/1b adangals/groovy/JSON-XML/example_2.json")
def json = new JsonSlurper().parse(f1)
def writer = new StringWriter()
def xmlf = new MarkupBuilder(writer)
xmlf.quiz{
subject('sport')
{q1{json.quiz.sport.q1.collect{s,t->
question(t.question)
options(t.options)
answer(t.answer) }}
subject('maths')
{q1{json.quiz.maths.q1.collect{q,r->
question(r.q1.question)
}}} }
}
println writer.toString()
我预期的结果会是这样
<quiz>
<subject>sport</subject>
<q1>
<question>krlsfnwlkf</question>
<options>NYB,LAK,GSW,HR</options>
<answer>fsfwrfw</answer>
</q1>
<subject> maths</subject>
<q1>
<question>csfwf</question>
<options>cadfa</options>
</q1>
</quiz>
1条答案
按热度按时间pu82cl6c1#
只需从这种访问器
json.quiz.sport.q1.collect
中删除q1
您可以使用
with
而不是collect
,因为您要回答一个问题/答案实验结果: