我正在使用groovy.json.JsonBuilder并且在指定字段名时遇到问题,该字段名也是当前作用域中变量的名称。
这有效:
System.out.println(new GroovyShell().evaluate(
"def builder = new groovy.json.JsonBuilder();"
+ "def age = 23;"
+ "builder.example {"
+ " name 'Fred';"
+ " 'age1' 27;"
+ " blah {"
+ " foo 'bar';"
+ " };"
+ "};"
+ "return builder.toPrettyString()"));
并产生输出:
{
"example": {
"name": "Fred",
"age1": 27,
"blah": {
"foo": "bar"
}
}
}
但这失败了(“年龄”字段由于某种原因与变量冲突):
System.out.println(new GroovyShell().evaluate(
"def builder = new groovy.json.JsonBuilder();"
+ "def age = 23;"
+ "builder.example {"
+ " name 'Fred';"
+ " 'age' 27;"
+ " blah {"
+ " foo 'bar';"
+ " };"
+ "};"
+ "return builder.toPrettyString()"));
并产生异常:
groovy.lang.MissingMethodException: No signature of method: java.lang.Integer.call() is applicable for argument types: (Integer) values: [27]
Possible solutions: wait(), abs(), any(), wait(long), wait(long, int), max(int, int)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:72)
at org.codehaus.groovy.runtime.callsite.PojoMetaClassSite.call(PojoMetaClassSite.java:48)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:128)
at Script1$_run_closure1.doCall(Script1.groovy:5)
at Script1$_run_closure1.doCall(Script1.groovy)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
我不想更改变量的名称。有没有办法强制 JsonBuilder 接受字段名称?正如你所看到的,我试图把它放在引号中,但这没有帮助。
凤凰求蛊
相关分类