Exclude fields serializing using Groovy JsonOutput

Viewed 1670

How to exclude specific fields from being serialized when using the JsonOutput.toJson(..) in groovy?

Given class:

class Dummy {
  String f1
  transient String f2
}

Code:

// synthetic getter and setter should be preserved
Dummy dummy = new Dummy(f1: "hello", f2: "world")
String json = JsonOutput. toJson(dummy )
println json

Will result in:

{"f1":"hello", "f2":"world"}

Should result in:

{"f1":"hello"}
3 Answers

if you're using groovy >= 2.5.0 you could use JsonGenerator.Options to exclude fields:

class Dummy {
    String f1
    String f2
}
def dummy = new Dummy(f1: "hello", f2: "world")
def generator = new groovy.json.JsonGenerator.Options()
    .excludeFieldsByName('f2')
    .build()
assert generator.toJson(dummy)=='{"f1":"hello"}'

Hope it helps.

Related