3

创建的 JSON 对象有两个附加属性:

  1. contentHash
  2. originalClassName

它们会自动添加,这是我不想要的。PFB 代码

class Info{
    def summary
    def description
}

class Simple{
    def start
    def finish
    def status
}


def buildJson(def info, def simple)
{
    def jsonBuilder = new groovy.json.JsonBuilder()
    jsonBuilder(info: info, simple: simple)
    jsonBuilder.toPrettyString()

}

从上面的代码创建的 Json-

{
    "info": {
        "contentHash": "a36cfa5d54ea40c843fff70e3e6e788e",
        "originalClassName": "Info",
        "summary":"Summary",
        "description": "Description"
    },
    "simple": [
        {
            "contentHash": "1aab6dd693268f65224940a03a51c25b",
            "start": "2017-09-10T08:54:05+0000",
            "originalClassName": "ExampleTest",
            "status": "PASS",
            "finish": "2017-09-10T08:54:16+0000"
        },
        {
            "contentHash": "1aab6dd693268f65224940a03a51c25b",
            "start": "2017-09-10T08:53:37+0000",
            "originalClassName": "ExampleTest",
            "status": "PASS",
            "finish": "2017-09-10T08:54:01+0000"
        }
    ]
}

我不想要这两个属性,我不确定为什么要首先添加它。有没有办法JSONObject直接生成exact。

4

1 回答 1

1

我在升级到 groovy 2.4.12 时遇到了这个问题。我通过定义 Object 类来解决这个问题

你可以试试

 def info = new Object()
 info.metaClass.summary = "Info"
 info.metaClass.description = "Description"

 def simple = new Object()
 simple.metaClass.start = "start"
 simple.metaClass.finish = "finish"
 simple.metaClass.status = "status"

 def buildJson(def info, def simple)
 {
   def jsonBuilder = new groovy.json.JsonBuilder()
   jsonBuilder(info: info, simple: simple)
   println jsonBuilder.toPrettyString()
 }

这将不包括元属性“originalClassName”和“contentHash”

于 2018-07-25T18:07:52.100 回答