Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy's JsonBuilder creates two additional attributes

JSON Object created has two additional attributes:

  1. contentHash
  2. originalClassName

They are getting added automatically, which I do not want. PFB the code

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 created from above code-

{
    "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"
        }
    ]
}

I do not want these two attributes, I am not sure of why is it getting added in first place. is there a way to generate exact JSONObject directly.

like image 946
Rahul Avatar asked Jan 28 '26 06:01

Rahul


1 Answers

I faced this issue while upgrading to groovy 2.4.12. I get through this by defining Object class

You can try

 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()
 }

This will not include meta attributes "originalClassName" and "contentHash"

like image 114
Kaustubh P Avatar answered Jan 31 '26 01:01

Kaustubh P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!