您可以使用 GroovyShell 来评估字符串并将脚本中调用的方法委托给 ObjectGraphBuilder。我重复了“发票”方法。如果这是不可接受的,请查看 Guillaume Laforge 的Going to Mars with Domain-Specific Languages,他在那里教授如何自定义编译器。
由于 ObjectGraphBuilder 的工作方式,我还创建了一个Invoices
类。如果这对您来说是动态的,请查看它的解析器。
import groovy.transform.ToString as TS
@TS class Invoices { List<Invoice> invoices=[] }
@TS class Invoice { List<Item> items=[]; Date date }
@TS class Item { Integer count; Product product }
@TS class Product { String name; Integer dollar; Vendor vendor }
@TS class Vendor { Integer id }
String myString = """
invoices {
invoice(date: new Date(106,1,2)){
item(count:5){
product(name:'ULC', dollar:1499)
}
item(count:1){
product(name:'Visual Editor', dollar:499)
}
}
invoice(date: new Date(106,1,2)){
item(count:4) {
product(name:'Visual Editor', dollar:499)
}
}
}
"""
invoicesParser = { Closure c ->
new ObjectGraphBuilder().invoices c
}
binding = new Binding( [invoices: invoicesParser] )
invoices = new GroovyShell(binding).evaluate myString
assert invoices.invoices.size() == 2
更新:至于您的第二个问题,我不知道,也找不到任何返回对象图构建器表示的方法。你可以自己动手,但我认为如果你尝试像 json 这样的东西会更好。您的用例是否允许您这样做?
use( groovy.json.JsonOutput ) {
assert invoices.toJson().prettyPrint() == """{
"invoices": [
{
"date": "2006-02-02T02:00:00+0000",
"items": [
{
"product": {
"vendor": null,
"dollar": 1499,
"name": "ULC"
},
"count": 5
},
{
"product": {
"vendor": null,
"dollar": 499,
"name": "Visual Editor"
},
"count": 1
}
]
},
{
"date": "2006-02-02T02:00:00+0000",
"items": [
{
"product": {
"vendor": null,
"dollar": 499,
"name": "Visual Editor"
},
"count": 4
}
]
}
]
}"""
}