Groovy的JsonBuilder创建了两个附加属性

8e2ybdfx  于 2022-11-01  发布在  其他
关注(0)|答案(2)|浏览(148)

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

  1. originalClassName
  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

deikduxw

deikduxw1#

我在升级到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()
 }

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

tf7tbtn2

tf7tbtn22#

指定默认生成器允许您排除这些字段-然而,在我看来,它们在默认情况下并没有被排除是很奇怪的:

def generator = new groovy.json.JsonGenerator.Options()
      .excludeFieldsByName('contentHash', 'originalClassName')
      .build()

 def builder = new JsonBuilder(jsonObject, generator)

相关问题