将Groovy对象转换为JSON Stackoverflow

时间:2015-06-16 17:22:19

标签: json groovy

我正在将一些XML转换为JSON,我使用Groovy的XmlSlurper来解析XML,然后构建一个具有所需结构的Groovy Map,然后我使用{{1或JsonOutput将该对象打印为JSON。这是代码:

JsonBuilder

一切似乎都很好,当我打印import groovy.json.* def X = """ <XML> <Rules> <Rule Alias="" EV="Height" Ht="0" InsuredId="1" Number="" QuestionTypeId="22" ResultType="None" Seq="0" Title="現在の身長・体重" Visible="false" Width="0">身長<Answer Alias="" Sev="0">170<Decision Product=""> <UnderwritingDecision Decision="ACC"/> </Decision> <Rule Alias="" EV="Weight" Ht="0" InsuredId="1" Number="" QuestionTypeId="21" ResultType="None" Seq="15" Visible="false" Width="0">体重<Answer Alias="" Sev="0">100<Decision Product=""> <UnderwritingDecision Decision="ACC"/> </Decision> <Rule Alias="NPCL" EV="Age" Ht="0" InsuredId="1" Number="" QuestionTypeId="1" ResultType="None" Seq="16" Title="NPCL" Visible="false" Width="0">年齢<Answer Alias="" Sev="0">34<Decision Product=""> <UnderwritingDecision Decision="ACC"/> </Decision> </Answer> </Rule> </Answer> </Rule> </Answer> </Rule> <Rule Alias="" ExtID="ImpairmentTag" Ht="0" InsuredId="1" Number="" QuestionTypeId="9" ResultType="None" Seq="1" Title="1項" Visible="true" Width="0">最近3ヶ月以内に、医師の診察・検査・治療・投薬を受けたことがありますか。<Answer Alias="" Sev="0">いいえ<Decision Product=""> <UnderwritingDecision Decision="ACC"/> </Decision> </Answer> </Rule> </Rules> </XML> """ def xml = new XmlSlurper().parseText(X) def nodeText = { it.nodeIterator().next().localText()[0] } def createQuestion createQuestion = { [ Text: nodeText(it), // answer could have other questions could be nested Answer: !it.Answer.Rule.isEmpty() ? [ nodeText(it.Answer), createQuestion(it.Answer.Rule)] : [nodeText(it.Answer)], InsuredId: it.'@InsuredId', Visible: it.'@Visible', CategoryText: it.'@Title', FieldTypeId: it.'@QuestionTypeId', ExitId: it.'@ExtID', Alias: it.'@Alias', Number: it.'@Number', ResultType: it.'@ResultType' ] } def v = xml.Rules.Rule.collect(createQuestion) assert v instanceof List assert v[0] instanceof Map assert v[0].Text instanceof String 时,它具有良好的结构。但是,当我使用v时,我会获得JsonOutput.toJson(v)。如果我使用java.lang.StackOverflowError,那么我得到如下几行:

new JsonBuilder(v)

groovy.json.JsonOutput.writeIterator(JsonOutput.java:442) at groovy.json.JsonOutput.writeObject(JsonOutput.java:272) at groovy.json.JsonOutput.writeIterator(JsonOutput.java:442) at groovy.json.JsonOutput.writeObject(JsonOutput.java:272) at groovy.json.JsonOutput.writeIterator(JsonOutput.java:442) 对象潜伏着周期性结构吗?

更奇怪的是 - 如果在上面的脚本末尾添加了以下行

v

你会进入控制台:

println v[0].Answer[1].Answer[1]
println JsonOutput.toJson(v[0].Answer[1].Answer[1])

0 个答案:

没有答案