1

如何让 ObjectGraphBuilder 从字符串构建我的类实例?我的意思是如果我有

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)
        }
    }
"""
  1. 如何将此字符串(myString)转换为发票类的实例(我假设我必须使用 ObjectGraphBuilder 但如何?)
  2. 给定类 invoice 的一个实例(及其所有嵌套属性),如何将该实例转换为 myString 之类的字符串?

我也希望能够从文本文件中序列化和反序列化,但我认为它与字符串相同。

4

1 回答 1

1

您可以使用 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
                }
            ]
        }
    ]
}"""
}
于 2013-05-31T02:23:24.460 回答