3

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.

Rao
  • 20,781
  • 11
  • 57
  • 77
Rahul
  • 39
  • 3
  • How are you calling `buildJson` method? – Rao Sep 11 '17 at 05:01
  • What is your groovy version? I can see your code is working as desired. Do not see any additional keys. See online demo - https://ideone.com/L35Z6a – Rao Sep 11 '17 at 05:10

2 Answers2

1

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"

Kaustubh P
  • 11
  • 1
1

Specifying a default generator allows you to exclude those fields - however seems odd to me that they aren't excluded by default:

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

 def builder = new JsonBuilder(jsonObject, generator)
ChristianO
  • 11
  • 4